在我的一个课程中,我有许多属性在获取和设置方面做了非常相似的事情。所以我将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源代码中寻找它。有谁知道我在哪里可以找到这些信息?
答案 0 :(得分:22)
这是 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__)
答案 1 :(得分:7)
property
是descriptor,因此您必须覆盖(或重新实现新对象)__get__()
, __set__()
, and __delete__()
methods。