如何在Python中实现描述符

时间:2017-10-31 15:34:53

标签: python python-3.x python-descriptors

我正在根据文档中的Property示例处理我自己的描述符:https://docs.python.org/3/howto/descriptor.html#properties

但由于某种原因,我所有的财产都是一样的。

class Property(object):
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

    def getter(self, fget):
        return type(self)(fget, self.fset, self.fdel, self.__doc__)

    def setter(self, fset):
        return type(self)(self.fget, fset, self.fdel, self.__doc__)

    def deleter(self, fdel):
        return type(self)(self.fget, self.fset, fdel, self.__doc__)

class Demo(object):

    def __init__(self, a=None, b=None):
        self._a = a
        self._b = b

    @Property
    def a(self):
        return self._a

    @a.setter
    def a(self, a):
        self._a = a

    @Property
    def b(self):
        return self._b

    @b.setter
    def a(self, b):
        self._b = b

d = Demo('4')
print(d.a, d.b)  # None None   (Should be: '4' None ?)
d.a = '3'
print(d.a, d.b)  # 3 3   (Should be: '3' None ?)

首先,为什么传递给构造函数的值没有按照我的意图设置/访问?为什么更改a似乎也会更改b

1 个答案:

答案 0 :(得分:2)

代码中有一个拼写错误。修复它会产生预期的输出。

@b.setter
def a(self, b):
    self._b = b

应该是:

@b.setter
def b(self, b):
    self._b = b