class a_class():
_x = []
@property
def x(self):
return a_class._x
ac1 = a_class()
print(a_class.x)
print(ac1.x)
为什么第一个打印返回属性对象,而第二个打印返回列表对象?
访问类上的属性不会调用它;它仅在实例上调用。如果要在类上调用它,则会破坏方法查找,因为方法查找从实例的类读取属性,而不是从实例本身读取属性。
class cls:
@property
def attr(self):
print('Property was called')
cls.attr # doesn't output anything, and evaluates to the property
cls().attr # calls the property, outputting the string