所有您的方法都是实例方法。它们都不是类方法。
方法的第一个参数命名为self 只是按照约定。您可以将其命名为任何您想要的名称,而将其命名为 cls 不会使其成为对该类的引用。第一个参数绑定到一个实例是由于方法查找的工作方式(访问C.getA_s 会产生一个绑定的方法对象,调用该对象会导致C 被传递到原始函数@ 987654327@),参数的名称不起作用。
在您的方法中,您只是在引用实例属性。 A 属性最终只在类上定义并不重要,您仍然通过C.A 访问该属性(其中C 是您创建的实例),而不是maclass.A。如果没有实例属性遮蔽它,则在实例上查找属性也会找到在类上定义的属性。
要使方法成为类方法,请用@classmethod decorator 装饰它:
@classmethod
def getA_c(cls):
print(cls.A)
现在cls 将始终是对类的引用,而不是对实例的引用。我需要再次强调,我为第一个参数选择的名称对于 Python 实际上并不重要,但cls 是这里的约定,因为这样更容易提醒读者此方法绑定到类对象。
请注意,如果您对getB_c() 方法执行此操作,那么尝试在该方法中访问cls.B 将失败,因为maclass 类对象上没有B 属性。
这是因为 classmethod 将函数包装在 descriptor object 中,从而覆盖了正常的函数绑定行为。正是描述符 protocol 导致方法在作为实例上的属性访问时绑定到实例,classmethod 对象重定向该绑定过程。
这是一个内联 cmets 的简短演示,我使用 Python 转换来命名类(使用 CamelCase),以及用于实例、属性、函数和方法(使用 snake_case):
>>> class MyClass():
... class_attribute = "String attribute on the class"
... def __init__(self):
... self.instance_attribute = "String attribute on the instance"
... @classmethod
... def get_class_attribute(cls):
... return cls.class_attribute
... def get_instance_attribute(self):
... return self.instance_attribute
... @classmethod
... def get_instance_attribute_on_class(cls):
... return cls.instance_attribute
...
>>> instance = MyClass()
>>> instance.class_attribute # class attributes are visible on the instance
'String attribute on the class'
>>> MyClass.class_attribute # class attributes are also visible on the class
'String attribute on the class'
>>> instance.get_class_attribute() # bound to the class, but that doesn't matter here
'String attribute on the class'
>>> instance.class_attribute = "String attribute value overriding the class attribute"
>>> instance.get_class_attribute() # bound to the class, so the class attribute is found
'String attribute on the class'
>>> MyClass.get_instance_attribute_on_class() # fails, there is instance_attribute on the class
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 12, in get_instance_attribute_on_class
AttributeError: type object 'MyClass' has no attribute 'instance_attribute'
请注意,即使我们在实例上设置了同名的属性,类方法也会访问类属性。
接下来是绑定行为:
>>> MyClass.get_instance_attribute # accessing the method on the class gives you the function
<function MyClass.get_instance_attribute at 0x10f94f268>
>>> instance.get_instance_attribute # accessing the method on the instance gives you the bound method
<bound method MyClass.get_instance_attribute of <__main__.MyClass object at 0x10f92b5f8>>
>>> MyClass.get_class_attribute # class methods are always bound, to the class
<bound method MyClass.get_class_attribute of <class '__main__.MyClass'>>
>>> instance.get_class_attribute # class methods are always bound, to the class
<bound method MyClass.get_class_attribute of <class '__main__.MyClass'>>
绑定的方法告诉你它们被绑定到什么到,调用方法传入绑定的对象作为第一个参数。也可以通过查看绑定方法的 __self__ 属性来内省该对象:
>>> instance.get_instance_attribute.__self__ # the instance
<__main__.MyClass object at 0x10f92b5f8>
>>> instance.get_class_attribute.__self__ # the class
<class '__main__.MyClass'>