在《核心Python编程》一书中,有一个关于如何使用属性的示例。代码如下:
class Hidex(object):
def __init__(self, x):
self.__x = x
@property
def x():
def fget(self):
return ~self.__x
def fset(self, x):
assert isinstance(val, int), 'val must be int'
self.__x = ~x
return locals()
书中说,这个类将使用以下代码:
inst = Hidex(20)
print inst.x
inst.x = 30
print inst.x
但我觉得这门课不行。因为当访问inst.x时,解释器将实际运行Hidex.__dict__['x'].__get__(x, Hidex)
,并且因为x=property(x),property的第一个参数'fget'是x,而不是x()中定义的函数'fget'
另外,当我运行此代码时,得到的结果是:
{'fget': <function fset at 0x.....>, 'self': <__main__.xxxx>, 'fget': <function fget at 0x....>}
traceback:
...... # this result is just telling t.x = 30 cannot run, just skip the details
AttributeError: cannot set attribute
我错过什么了吗?为什么这本书能起作用
这很有意义:
看起来你的问题代码中的
@property
不是内置的,而是另一个版本这很可能是本文的意图:
相关问题 更多 >
编程相关推荐