1
class ClassA:
    A = 10
    def __init__(self):
        self.a = 10
        self.b = 20

    def methodA(self):
        return self.A

 obj = ClassA()
 print(obj.methodA()) # returns 10

这显然有限制,其中我 obj 将没有名称为“A”的属性。但是为什么 python 会通过self.A. 将其退回是否更好ClassA.A

4

1 回答 1

3

This is entirely by design.

Methods on classes are attributes on the class too (albeit enhanced by being descriptors as well). This is how self.methodA() would be located too.

Python searches attributes first on the instance, then the class, then the base classes of the class.

Note that setting self.A will still set the value on the instance, thereby masking the class attribute. This lets classes specify default values for attributes, to be replaced by values on the instance later on.

This all doesn't preclude you from accessing ClassA.A directly and bypass the instance dictionary. If you wanted to change the shared value, you'd have to assign directly to ClassA.A for the above reason.

于 2013-11-07T17:08:40.487 回答