我正在编写一个修改类的函数。目前我这样做(从我的单元测试中复制):
class ChildClass:
def __init__(self):
self.foo = 123
class Subject:
def __init__(self):
self.child = ChildClass()
# This is the function I'm talking about. It modifies the class "Subject".
defer_property(Subject, "child", "foo")
assertEqual(123, Subject().foo)
由于函数修改了类,我宁愿在类定义中运行它,如下所示:
class Subject:
defer_property("child", "foo")
def __init__(self):
self.child = ChildClass()
如果函数可以从上下文获取对类的引用,那将是很好的:
def defer_property(member, property_name):
cls = get_class_reference_somehow() # I want this magic function
prop = property(
# ...
)
setattr(cls, property_name, prop)
这可能吗?
达到类似目的的任何替代方式都很棒。我真的不想涉及元类。
答案 0 :(得分:4)
达到类似目标的任何其他方式都很棒。
装饰:
def defer_property(member, property_name):
def _(cls):
pass # do stuff here
return cls
return _
用法:
@defer_property("child", "foo")
class Subject:
pass
答案 1 :(得分:3)
在评估主体之前,该类不存在,所以没有。一个类声明
class MyClass(object):
foo = 3
def __init__(self):
pass
大致相当于
body['foo'] = 3
def init(self):
pass
body['__init__'] = init
# *Now* create the class object
MyClass = type('MyClass', (object,), body)
答案 2 :(得分:1)
您的功能不必自行设置属性,而是可以返回它:
def defer_property(member, property_name):
prop = property(
# ...
)
return prop
class Subject:
foo = defer_property("child", "foo")