Skip to main content
 首页 » 编程设计

python之我可以在描述符的 __init__ 方法期间获得对 'owner' 类的引用吗

2025年05月04日18sky-heaven

是否可以在该描述符的 __init__ 函数期间访问该描述符内的“所有者”类,而无需像本例中那样手动传递它?

class FooDescriptor(object): 
    def __init__(self, owner): 
        #do things to owner here 
        setattr(owner, 'bar_attribute', 'bar_value') 
 
 
class BarClass(object): 
    foo_attribute = FooDescriptor(owner=BarClass) 

请您参考如下方法:

做类似事情的一种方法是使用元类。只要确保它真的是你想要的,如果你不明白它是如何工作的,就不要盲目复制。

class Descriptor(object): 
    pass 
 
class Meta(type): 
    def __new__(cls, name, bases, attrs): 
        obj = type.__new__(cls, name, bases, attrs) 
        # obj is now a type instance 
 
        # this loop looks for Descriptor subclasses 
        # and instantiates them, passing the type as the first argument 
        for name, attr in attrs.iteritems(): 
            if isinstance(attr, type) and issubclass(attr, Descriptor): 
                setattr(obj, name, attr(obj)) 
 
        return obj 
 
class FooDescriptor(Descriptor): 
    def __init__(self, owner): 
        owner.foo = 42 
 
class BarClass(object): 
    __metaclass__ = Meta 
    foo_attribute = FooDescriptor # will be instantiated by the metaclass 
 
print BarClass.foo 

如果您需要传递额外的参数,您可以使用例如一个 (class, args) 的元组来代替类,或者使 FooDescriptor 成为一个装饰器,它会返回一个在 ctor 中只接受一个参数的类。