classes1.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. class Animal:
  2. def says(self):
  3. return 'I speak!'
  4. class Horse(Animal):
  5. def says(self):
  6. return 'Neigh!'
  7. class Donkey(Animal):
  8. def says(self):
  9. return 'Hee-haw!'
  10. class Mule(Donkey, Horse):
  11. pass
  12. class Hinny(Horse, Donkey):
  13. pass
  14. def test_animals():
  15. mule = Mule()
  16. hinny = Hinny()
  17. print(mule.says())
  18. print(hinny.says())
  19. print(Mule.mro())
  20. print(Mule.__mro__)
  21. # Миксины
  22. class Super():
  23. def dump(self):
  24. print('Super!!!')
  25. class PrettyMixin():
  26. def dump(self):
  27. import pprint
  28. pprint.pprint(vars(self))
  29. class Thing(Super, PrettyMixin):
  30. pass
  31. def test_mixin():
  32. t = Thing()
  33. t.name = "Nyarlathotep"
  34. t.feature = 'ichor'
  35. t.age = 'eldritch'
  36. t.dump()
  37. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  38. # Инструкция property
  39. class Duck():
  40. def __init__(self, input_name) -> None:
  41. self.hidden_name = input_name
  42. def get_name(self):
  43. print('inside the getter')
  44. return self.hidden_name
  45. def set_name(self, input_name):
  46. print('inside the setter')
  47. self.hidden_name = input_name
  48. name = property(get_name, set_name)
  49. class ImprovedDuck():
  50. def __init__(self, input_name) -> None:
  51. self.__name = input_name
  52. @property
  53. def name(self):
  54. print('inside the getter')
  55. return self.__name
  56. @name.setter
  57. def name(self, input_name):
  58. print('inside the setter')
  59. self.__name = input_name
  60. def set_property():
  61. # don = Duck('Donald')
  62. don = ImprovedDuck('Donald')
  63. print(don.name)
  64. don.name = 'Donna'
  65. print(don.name)
  66. print(don._ImprovedDuck__name)
  67. # set_property()
  68. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  69. # Методы классов @classmethod
  70. class A():
  71. count = 0
  72. def __init__(self):
  73. A.count += 1
  74. def exclaim(self):
  75. print('I`m an A!')
  76. @classmethod
  77. def kids(cls):
  78. print("A has", cls.count, "little objects.")
  79. def test_classmethod():
  80. easy_a = A()
  81. breezy_a = A()
  82. wheezy_a = A()
  83. A.kids()
  84. # test_classmethod()
  85. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  86. # Статические методы @staticmethod
  87. class CoyoteWeapon():
  88. @staticmethod
  89. def commercial():
  90. print('This CoyoWeapon has been brought to you by Acme')
  91. def test_staticmethod():
  92. CoyoteWeapon.commercial()
  93. # test_staticmethod()