【问题标题】:Why isn't this classprop implementation working?为什么这个 classprop 实现不起作用?
【发布时间】:2011-04-14 04:08:31
【问题描述】:

基于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
>>> 

我做错了什么?

(而且我已经看到它的实现有点不同。我特别想知道为什么 这个 实现不起作用。)

【问题讨论】:

    标签: python class properties descriptor class-method


    【解决方案1】:

    The doc's say:

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

    __get__ 不同,它没有提及类属性。所以 Python 不会在类属性上调用 any __set__

    【讨论】:

    • 为什么X 不是实例而type 是类?
    • 实例和类型不同,写入它们也是如此。 Python 只是没有按照您希望的方式实现描述符。
    猜你喜欢
    • 2011-01-12
    • 1970-01-01
    • 2021-04-23
    • 2016-05-08
    • 2021-12-15
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多