Skip to main content
 首页 » 编程设计

python之在类定义内运行的函数能否找到对该类的引用

2025年05月04日14mfryf

我正在编写一个修改类的函数。目前我是这样做的(从我的单元测试中复制):

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) 

这可能吗?

任何达到类似目的的替代方法都会很棒。不过,我真的不想涉及元类。

请您参考如下方法:

Any alternative way to reach a similar goal end be awesome.

装饰器:

def defer_property(member, property_name): 
    def _(cls): 
        pass # do stuff here 
        return cls 
    return _ 

用法:

@defer_property("child", "foo") 
class Subject: 
    pass