123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- '''
- @classmethod
- @staticmethod
- classmethod - привязывает функцию к клсассу. Вызывается от класса.
- staticmethod - Вызывается от класса или экземпляра.
- '''
- class Example1:
- @classmethod
- def class_hello(cls):
- print(f'class_hello {cls}')
-
- class Example2:
- @staticmethod
- def static_hello():
- print('static hello')
- class Date:
- def __init__(self, day, month, year):
- self.day = day
- self.month = month
- self.year = year
-
- @staticmethod
- def from_str(data):
- data = data.split('-')
- return Date(int(data[0], base=10), int(data[1], base=10),
- int(data[2], base=10))
- def test_1():
- day_1 = Date(20, 9, 1997)
- print(day_1.day)
- print(day_1.month)
- print(day_1.year)
- day_2 = Date(1, 2, 2003)
- print(day_2.day, day_2.month, day_2.year)
- def test_2():
- day_1 = Date.from_str('12-4-2024')
- day_2 = Date.from_str('06-09-2022')
- print(day_1.day, day_1.month, day_1.year)
- print(day_2.day, day_2.month, day_2.year)
- #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- class Pizza:
- def __init__(self, ingredients=None):
- if ingredients is None:
- ingredients = []
- self.ingredients = ingredients
- @staticmethod
- def margherita():
- return Pizza(['mozzarella', 'tomatoes'])
-
- @staticmethod
- def peperoni():
- return Pizza(['mozzarella', 'peperoni', 'tomatoes'])
-
- @staticmethod
- def barbecue():
- return Pizza(['mozzarella', 'red onion', 'sauce bbq', 'chicken'])
- def test_3():
- bbq = Pizza.barbecue()
- peperoni = Pizza.peperoni()
- margherita = Pizza.margherita()
- print(sorted(bbq.ingredients))
- print(sorted(peperoni.ingredients))
- print(sorted(margherita.ingredients))
- def main():
- # test_1()
- # test_2()
- test_3()
- if __name__ == '__main__':
- main()
|