为什么作为列表的类级别计算属性返回一个属性对象,但相同的实例级别返回“正确的对象”?

问题描述 投票:0回答:1
class a_class():
    _x = []

    @property
    def x(self):
        return a_class._x

ac1 = a_class()

print(a_class.x)

print(ac1.x)

为什么第一个打印返回属性对象,而第二个打印返回列表对象?

python class properties instance
1个回答
0
投票

访问类上的属性不会调用它;它仅在实例上调用。这是因为当在类上查找方法时,调用它会违背 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
© www.soinside.com 2019 - 2024. All rights reserved.