1

我正在根据文档中的属性示例处理我自己的描述符: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也在变化?

4

1 回答 1

2

代码中有错别字。修复它会产生预期的输出。

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

应该:

@b.setter
def b(self, b):
    self._b = b
于 2017-10-31T16:55:22.490 回答