meta_1.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. '''
  2. __new__ - вызывается для фактического создания нового объекта.
  3. Он статический, т.к. экземпляра класса еще не существует
  4. Метод __new__ не вызывает __init__.
  5. class object:
  6. @staticmethod
  7. def __new__(cls, *more):
  8. pass
  9. '''
  10. class Point:
  11. def __new__(cls, *args, **kwargs):
  12. print('Point: Создание экземпляра')
  13. instance = object.__new__(cls)
  14. return instance
  15. def __init__(self, x, y):
  16. print('Point: Инициализация экземпляра')
  17. self.x = x
  18. self.y = y
  19. def test_1():
  20. p = object.__new__(Point)
  21. p.__init__(10, 20)
  22. print(p)
  23. print(type(p))
  24. print(p.__dict__)
  25. class Point3D(Point):
  26. def __new__(cls, *args, **kwargs):
  27. print('Point3D: Создание экземпляра')
  28. instance = super().__new__(cls) # вызываем через super
  29. return instance
  30. def __init__(self, x, y, z):
  31. print('Point3D: Инициализация экземпляра')
  32. super().__init__(x, y)
  33. self.z = z
  34. def test_2():
  35. p = Point3D(10, 20, 30)
  36. print(p.__dict__)
  37. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  38. '''Создание атрибутов и методов в методе __new__'''
  39. class SquareNumber(int):
  40. def __new__(cls, value):
  41. return super().__new__(cls, value ** 2)
  42. def test_3():
  43. x = SquareNumber(3)
  44. print(x)
  45. print(isinstance(x, int))
  46. class Square:
  47. def __new__(cls, w, h):
  48. # Реализация метода area
  49. cls.area = lambda self: self.width * self.height
  50. setattr(cls, 'perimeter', lambda self: 2 * (self.width + self.height))
  51. instance = super().__new__(cls)
  52. instance.width = w
  53. instance.height = h
  54. return instance
  55. def __init__(self, w, h):
  56. self.width = w
  57. self.height = h
  58. def test_4():
  59. s = Square(3, 4)
  60. print(s)
  61. print(s.area())
  62. print(s.perimeter())
  63. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  64. '''Вызов __new__ в качестве статического метода
  65. object.__new__(Square, 3, 4)
  66. Square.__new__(Square, 3, 4)
  67. '''
  68. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  69. '''Возвращаемое значение метода __new__'''
  70. class Person:
  71. def __new__(cls, *args, **kwargs):
  72. print(f'Создание экземпляра {cls.__name__}')
  73. instance = super().__new__(cls)
  74. return instance
  75. def __init__(self):
  76. print(f'Инициализация экземпляра {self.__class__.__name__}')
  77. def test_5():
  78. p = Person()
  79. '''
  80. Здесь вызов __inti__ не произойдет, т.к. __new__
  81. не возвращает экземпляр класаа
  82. '''
  83. class NewPerson:
  84. def __new__(cls, *args, **kwargs):
  85. print(f'Создание экземпляра {cls.__name__}')
  86. instance = 'Hellow world'
  87. return instance
  88. def __init__(self):
  89. print(f'Инициализация экземпляра {self.__class__.__name__}')
  90. def test_6():
  91. p = NewPerson()
  92. class BestPerson:
  93. def __new__(cls, name, age):
  94. instance = super().__new__(cls)
  95. instance.name = name
  96. instance.age = age
  97. return instance
  98. def test_7():
  99. p = BestPerson('Jackie Chan', 69)
  100. print(p.__dict__)
  101. def main():
  102. # test_1()
  103. # test_2()
  104. # test_3()
  105. # test_4()
  106. # test_5()
  107. # test_6()
  108. test_7()
  109. if __name__ == '__main__':
  110. main()