Answer

Answer

t.me/python_tesst

Ответ:

- my_metaclass.__new__ - Creating class instance of type <class '__main__.my_metaclass'>
- my_metaclass.__init__ - Initializing the class instance <class '__main__.C'>
- my_class_decorator - Chance to modify the class <class '__main__.C'>
- my_metaclass.__call__ - Creating object of type <class '__main__.C'>
- C.__new__ - Creating object.
- C.__init__ - Initializing object.
Object c = <__main__.C object at 0x7f7b480ce580>

Объяснение:

Предположим, что некий класс C имеет метакласс my_metaclass и декорирован с помощью my_class_decorator. Далее предположим, что my_metaclass представляет собой класс, полученный из type. Можно ожидать, что my_metaclass.__new__ вызывается первым. Затем следует my_metaclass.__init__, затем my_class_decorator. В этот момент класс C полностью готов к использованию. Когда мы вызываем C для создания объекта, который вызывает my.metaclass.__call__ (каждый раз при вызове объекта Python пытается вызвать __call__), затем type.__call__ вызывает C.__new__, наконец, вызывается C.__init__.

Код:

class my_metaclass(type):
   def __new__(cls, class_name, parents, attributes):
       print('- my_metaclass.__new__ - Creating class instance of type', cls)
       return super().__new__(cls, class_name, parents, attributes)
 
   def __init__(self, class_name, parents, attributes):
       print('- my_metaclass.__init__ - Initializing the class instance', self)
       super().__init__(class_name, parents, attributes)
 
   def __call__(self, *args, **kwargs):
       print('- my_metaclass.__call__ - Creating object of type ', self)
       return super().__call__(*args, **kwargs)
 
 
def my_class_decorator(cls):
   print('- my_class_decorator - Chance to modify the class', cls)
   return cls


@my_class_decorator
class C(metaclass=my_metaclass):
 
   def __new__(cls):
       print('- C.__new__ - Creating object.')
       return super(C, cls).__new__(cls)
 
   def __init__(self):
       print('- C.__init__ - Initializing object.')
 
c = C()
print('Object c =', c)

Report Page