method_1.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. '''
  2. @classmethod
  3. @staticmethod
  4. classmethod - привязывает функцию к клсассу. Вызывается от класса.
  5. staticmethod - Вызывается от класса или экземпляра.
  6. '''
  7. class Example1:
  8. @classmethod
  9. def class_hello(cls):
  10. print(f'class_hello {cls}')
  11. class Example2:
  12. @staticmethod
  13. def static_hello():
  14. print('static hello')
  15. class Date:
  16. def __init__(self, day, month, year):
  17. self.day = day
  18. self.month = month
  19. self.year = year
  20. @staticmethod
  21. def from_str(data):
  22. data = data.split('-')
  23. return Date(int(data[0], base=10), int(data[1], base=10),
  24. int(data[2], base=10))
  25. def test_1():
  26. day_1 = Date(20, 9, 1997)
  27. print(day_1.day)
  28. print(day_1.month)
  29. print(day_1.year)
  30. day_2 = Date(1, 2, 2003)
  31. print(day_2.day, day_2.month, day_2.year)
  32. def test_2():
  33. day_1 = Date.from_str('12-4-2024')
  34. day_2 = Date.from_str('06-09-2022')
  35. print(day_1.day, day_1.month, day_1.year)
  36. print(day_2.day, day_2.month, day_2.year)
  37. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  38. class Pizza:
  39. def __init__(self, ingredients=None):
  40. if ingredients is None:
  41. ingredients = []
  42. self.ingredients = ingredients
  43. @staticmethod
  44. def margherita():
  45. return Pizza(['mozzarella', 'tomatoes'])
  46. @staticmethod
  47. def peperoni():
  48. return Pizza(['mozzarella', 'peperoni', 'tomatoes'])
  49. @staticmethod
  50. def barbecue():
  51. return Pizza(['mozzarella', 'red onion', 'sauce bbq', 'chicken'])
  52. def test_3():
  53. bbq = Pizza.barbecue()
  54. peperoni = Pizza.peperoni()
  55. margherita = Pizza.margherita()
  56. print(sorted(bbq.ingredients))
  57. print(sorted(peperoni.ingredients))
  58. print(sorted(margherita.ingredients))
  59. def main():
  60. # test_1()
  61. # test_2()
  62. test_3()
  63. if __name__ == '__main__':
  64. main()