class a_class():
_x = []
@property
def x(self):
return a_class._x
ac1 = a_class()
print(a_class.x)
print(ac1.x)
为什么第一个打印返回属性对象,而第二个打印返回列表对象?
访问类上的属性不会调用它;它仅在实例上调用。这是因为当在类上查找方法时,调用它会违背 OOP 的目的。
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