为什么这个 classprop 实现不起作用?
基于我之前的一个问题询问,我试图想出一个允许设置和获取的类属性。所以我写了这个并将其放入模块 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
>>>
我做错了什么?
(我已经看到这个实现的工作方式有点不同。我特别想知道为什么这个实现不起作用。)
Based on a question I previously asked, I tried to come up with a class property that would allow setting as well as getting. So I wrote this and put it in a module 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)
While getting is working, setting doesn't seem to be getting called:
>>> util.X.x
1
>>> util.X.x = 1
>>>
What am I doing wrong?
(And I have seen implementations of this that work a bit differently. I'm specifically wanting to know why this implementation isn't working.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
文档说:
与
__get__
不同,它没有提及类属性。因此,Python 不会对类属性调用 any__set__
。The doc's say:
Unlike for
__get__
, it does not mention class attributes. So Python won't call any__set__
on a class attribute.