Python属性getter和setter decorator不可调用

mag*_*e25 2 python

我正在做类似以下的事情

class Parrot(object):
    def __init__(self):
        self.__voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self.__voltage
Run Code Online (Sandbox Code Playgroud)

然而,它将电压属性视为int,所以当我这样打电话时

p = Parrot()
print(p.voltage())
Run Code Online (Sandbox Code Playgroud)

我明白了

TypeError: 'int' object is not callable
Run Code Online (Sandbox Code Playgroud)

我试过用一个和两个强调来破坏电压属性名称.

Pet*_*per 8

getter的重点是它返回值而不被调用. p.voltage返回整数对象,因此运行p.voltage()等价于100()或等.

仍然可能存在要调用属性值的情况,例如,如果值本身是函数.但你在这里不需要它.