Can I get a reference to the 'owner' class during the __init__ method of a descriptor?

前端 未结 2 1934
天涯浪人
天涯浪人 2021-01-24 13:51

Is it possible to access the \'owner\' class inside a descriptor during the __init__ function of that descriptor, without passing it in manually as in this example?

2条回答
  •  盖世英雄少女心
    2021-01-24 14:09

    Since Python 3.6, you can use the __set_name__ special method:

    class FooDescriptor(object):
        def __set_name__(self, owner, name):
            owner.foo = 42
    
    class BarClass(object):
        foo_attribute = FooDescriptor()
    
    # foo_attribute.__set_name__(BarClass, "foo_attribute") called after class definition
    

    __set_name__ is automatically called on all descriptors in a class immediately after the class is created. See PEP 487 for more details.

提交回复
热议问题