19

在我的一门课程中,我有许多属性在获取和设置方面做非常相似的事情。所以我将参数抽象property为一个工厂函数:

def property_args(name):
    def getter(self):
        # do something
        return getattr(self, '_' + name)
    def setter(self, value)
        # do something
        setattr(self, '_' + name, value)
    return getter, setter

class MyClass(object):
    def __init__(self):
        self._x = None
    x = property(*property_args('x'))  # obviously there's more than one of these IRL

但是,我后来发现它property实际上是一个类,并且对它进行子类化将是完美的。我在文档中找不到任何解释我需要覆盖的内容(以及__init__等的参数签名),我真的不想在 C 源代码中寻找它。有谁知道我在哪里可以找到这些信息?

4

2 回答 2

26

这是property()中代码的纯 Python 等效项:

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__)
于 2012-09-13T11:50:20.293 回答
7

property是一个描述符,因此您必须覆盖(或在新对象上重新实现)__get__()__set__()__delete__()methods

于 2012-09-13T11:50:24.697 回答