基于
a question I previously asked
,我试图想出一个类属性,它既允许设置,也允许获取。所以我写了这个并把它放到一个模块里
util
:
class classprop(object):
def __init__(self, fget, fset=None):
if isinstance(fget, classmethod):
self.fget = fget
else:
self.fget = classmethod(fget)
if not fset or isinstance(fset, classmethod):
self.fset = fset
else:
self.fset = classmethod(fset)
def __get__(self, *a):
return self.fget.__get__(*a)()
def __set__(self, cls, value):
print 'In __set__'
if not self.fset:
raise AttributeError, "can't set attribute"
fset = self.fset.__get__(cls)
fset(value)
class X(object):
@classmethod
def _get_x(cls):
return 1
@classmethod
def _set_x(cls, value):
print 'You set x to {0}'.format(value)
x = classprop(fget=_get_x, fset=_set_x)
当“获取”工作时,设置似乎没有被调用:
>>> util.X.x
1
>>> util.X.x = 1
>>>
我做错什么了?
(我也看到了这种方法的实现有点不同。我特别想知道为什么
这
实现不起作用。)