gpt4 book ai didi

python - 子类化 Python 的 `property`

转载 作者:IT老高 更新时间:2023-10-28 21:09:52 25 4
gpt4 key购买 nike

在我的一门类(class)中,我有许多属性在获取和设置方面执行非常相似的操作。所以我把 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 源代码中寻找为了它。有谁知道我在哪里可以找到这些信息?

最佳答案

这是 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__)

关于python - 子类化 Python 的 `property`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12405087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com