Python property装饰器的getter和setter调用异常求助
Python Property装饰器使用错误排查
我尝试在Python中使用基于property的getter和setter,但遇到了异常问题。测试代码如下:
class anyThing(object): def __init__(self): self._xyz = 'something' @property def XYZ(self): return self._xyz @XYZ.setter def XYZ(self, value): self._xyz = value t = anyThing() # Construct an instance print(f'Type of t.XYZ is {type(t.XYZ)}') print(f'Invoking getter {t.XYZ()}') t.XYZ('anotherThing') # Invoke instance setter
执行代码后出现以下错误:
(PR) jonathan@jfgdev:/PR$ ./testProperty.py Type of t.XYZ is <class 'str'> Traceback (most recent call last): File "/mnt/ProgrammingRenaissance/./testProperty.py", line 17, in <module> print(f'Invoking getter {t.XYZ()}') TypeError: 'str' object is not callable
注释掉getter调用后,调用setter时也会出现类似的"不可调用"错误。改用传统的getter和setter方法则可正常运行,该问题在Python 3.10.6和3.10.10版本中均存在。
问题原因
你混淆了property装饰器的使用逻辑:
- 被
@property装饰的方法,访问时不需要加括号(),它会直接返回属性值,而非方法对象。所以t.XYZ已经是字符串'something',调用t.XYZ()自然会触发"str对象不可调用"的报错。 - 对应的setter方法,也不是通过函数调用的方式赋值,而是直接使用赋值语句
t.XYZ = 值来触发。
修正后的代码
class anyThing(object): def __init__(self): self._xyz = 'something' @property def XYZ(self): return self._xyz @XYZ.setter def XYZ(self, value): self._xyz = value t = anyThing() # Construct an instance print(f'Type of t.XYZ is {type(t.XYZ)}') print(f'Invoking getter {t.XYZ}') # 直接访问属性,无需括号 t.XYZ = 'anotherThing' # 使用赋值语句调用setter print(f'After setting, t.XYZ is {t.XYZ}')
执行结果
Type of t.XYZ is <class 'str'> Invoking getter something After setting, t.XYZ is anotherThing
内容的提问来源于stack exchange,提问作者Jonathan
相关产品推荐
相关产品推荐

