# 元类钩子

#__init__​、__new__​、__call__

见元类概述

# __init_subclass__

class MyBaseClass:
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        if not hasattr(cls, 'required_attribute'):
            raise TypeError(f"{cls.__name__} is missing the required attribute 'required_attribute'")

class MySubClass(MyBaseClass):
    required_attribute = 'some value'

class MyOtherSubClass(MyBaseClass):
    pass

# TypeError: MyOtherSubClass is missing the required attribute 'required_attribute'

#__set_name__​​

当定义了__set_name__​的方法被作为右值赋值时,会自动触发这一方法-目前分析主要用于描述符协议中。

class Bar:
    def __set_name__(self, owner, name):
        print(f'{self} was named {name} by {owner}')

class Foo:
    x = Bar()
    y = Bar()

"""
<__main__.Bar object at 0x000001CF9D9FB7C0> was named x by <class '__main__.Foo'>
<__main__.Bar object at 0x000001CF9D5AA880> was named y by <class '__main__.Foo'>
"""