简体   繁体   English

Python class 属性的正确语法参考

[英]Proper syntactic reference for Python class attributes

Having known the difference between class and instance attributes in Python, which of these two is the proper way to reference a class attribute?已经知道 class 和 Python 中的实例属性之间的区别,这两者中哪一个是引用 class 属性的正确方法?

import requests


class SomePage:
    
    PAGE_URL = 'www.someurl.com'

    def __init__(self) -> None:
        # Option A
        self.request_a = requests.get(self.PAGE_URL)
        # Option B
        self.request_b = requests.get(SomePage.PAGE_URL)

The result would be the same for any option.对于任何选项,结果都是相同的。 Is there any of them preferable?有没有更可取的?

These are not the same, so what you use depends on what you intend.这些是不一样的,所以你使用什么取决于你的意图。 This becomes clear if we consider the following example:如果我们考虑以下示例,这将变得很清楚:

class Foo:
    bar = 42
    def method1(self):
        return self.bar
    def method2(self):
        return Foo.bar

class Baz(Foo):
    bar = 99

baz = Baz()

In the repl:在repl中:

>>> baz.method1()
99
>>> baz.method2()
42

So, self.PAGE_URL will check the instance namespace, then the class namespace, then all the namespaces in the classes method resolution order .因此, self.PAGE_URL检查实例命名空间,然后是 class 命名空间,然后是类方法解析顺序中的所有命名空间

On the other hand Foo.bar will check Foo 's namespace, then all namespaces in Foo's method resolution order .另一方面Foo.bar检查Foo的命名空间,然后检查 Foo 的方法解析顺序中的所有命名空间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM