Python metaclasses: Why isn't __setattr__ called for attributes set during class definition?

后端 未结 4 1583
耶瑟儿~
耶瑟儿~ 2020-12-15 07:46

I have the following python code:

class FooMeta(type):
    def __setattr__(self, name, value):
        print name, value
        return super(FooMeta, self).         


        
4条回答
  •  别那么骄傲
    2020-12-15 07:54

    During the class creation, your namespace is evaluated to a dict and passed as an argument to the metaclass, together with the class name and base classes. Because of that, assigning a class attribute inside the class definition wouldn't work the way you expect. It doesn't create an empty class and assign everything. You also can't have duplicated keys in a dict, so during class creation attributes are already deduplicated. Only by setting an attribute after the class definition you can trigger your custom __setattr__.

    Because the namespace is a dict, there's no way for you to check duplicated methods, as suggested by your other question. The only practical way to do that is parsing the source code.

提交回复
热议问题