metaclass_2.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. class CustomType(type):
  2. def __new__(cls, name, bases, class_dict):
  3. print('Запуск создания нового типа данных!')
  4. # делегируем создание объекта через super
  5. # в данном случае родитель - это класс type
  6. cls_obj = super().__new__(cls, name, bases, class_dict)
  7. cls_obj.say_hello = lambda self: f'Hello, my name is {self.name}'
  8. return cls_obj
  9. class Person(metaclass=CustomType):
  10. def __init__(self, name, age):
  11. self.name = name
  12. self.age = age
  13. def greeting(self):
  14. return f'Hi, I am {self.name}. I am {self.age} years old.'
  15. def test_1():
  16. print(Person)
  17. print('Type of Person is', type(Person))
  18. print('Person is isinstance of CustomType', isinstance(Person, CustomType))
  19. print('Person is isinstance of type', isinstance(Person, type))
  20. p = Person('Ivan', 25)
  21. print(p.greeting())
  22. print(p.say_hello())
  23. def main():
  24. test_1()
  25. if __name__ == '__main__':
  26. main()