【发布时间】:2024-04-22 01:30:02
【问题描述】:
在我的一门课程中,我有许多属性在获取和设置方面执行非常相似的操作。所以我把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 源代码中寻找它。有谁知道我在哪里可以找到这些信息?
【问题讨论】:
-
作为参考,C实现可以在这里找到:hg.python.org/cpython/file/tip/Objects/descrobject.c
-
@nneonneo:谢谢!第 1228 行的大注释块就是答案。如果你想写一个完整的答案,那么我会接受。
-
很遗憾你可以回答你自己的问题:)
-
@BurhanKhalid 但 nneonneo 值得称赞!
标签: python properties