这是代码:
def Property(func):
return property(**func())
class A:
def __init__(self,name):
self._name = name
@Property
def name():
doc = 'A''s name'
def fget(self):
return self._name
def fset(self,val):
self._name = val
fdel = None
print locals()
return locals()
a = A('John')
print a.name
print a._name
a.name = 'Bob'
print a.name
print a._name
以上产生以下输出:
{'doc': 'As name','fset': <function fset at 0x10b68e578>,'fdel': None,'fget': <function fget at 0x10b68ec08>}
John
John
Bob
John
代码取from here.
问题:怎么了?它应该是简单的东西,但我找不到它.
注意:我需要属性来进行复杂的获取/设置,而不是简单地隐藏属性.
提前致谢.
解决方法
documentation for
property()声明:
Return a property attribute for new-style classes (classes that derive from object).
您的类不是新样式的类(您没有从对象继承).将类声明更改为:
class A(object):
...
它应该按预期工作.