为什么这个 classprop 实现不起作用?

发布于 2024-09-24 07:53:33 字数 1221 浏览 6 评论 0原文

基于我之前的一个问题询问,我试图想出一个允许设置和获取的类属性。所以我写了这个并将其放入模块 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

得不到的就毁灭 2024-10-01 07:53:33

文档说:

object.__set__(自身,实例,
value)
调用以设置属性
所有者的实例实例
类到一个新值,

__get__不同,它没有提及类属性。因此,Python 不会对类属性调用 any __set__

The doc's say:

object.__set__(self, instance,
value)
Called to set the attribute on
an instance instance of the owner
class to a new value, value.

Unlike for __get__, it does not mention class attributes. So Python won't call any __set__ on a class attribute.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文