123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- '''Декорирование классов'''
- '''Обычный декоратор'''
- from functools import wraps
- def header_h1(func):
- @wraps(func)
- def inner(*args, **kwargs):
- result = func(*args, **kwargs)
- return f'<h1>{result}</h1>'
- return inner
- def header_h2(func):
- def wrapper(*args, **kwargs):
- result = func(*args, **kwargs)
- return f'<h2>{result}<h2>'
- return wrapper
- @header_h2
- def say_hello_to(name, surname):
- return f'Hello {name} {surname}'
- def test_1():
- res = say_hello_to('Vasya', 'Ivanov')
- print(f'{res=}')
- '''Создание атрибутов в классе при помощи декоратора'''
- '''
- def custom_settings(cls):
- cls.host = '127.0.0.1'
- cls.port = 80
- return cls
- '''
- def custom_settings(host='127.0.0.1', port=10):
- def decorator(cls):
- cls.host = host
- cls.port = port
- return cls
- return decorator
- @custom_settings(port=99)
- class Settings:
- pass
- @custom_settings(host='10.32.2.43', port=19)
- class Settings2:
- pass
- def test_2():
- print(Settings.host, Settings.port)
- print(Settings2.host, Settings2.port)
- #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- '''Создание методов в классе при помощи декоратора'''
- def add_hello(cls):
- cls.hello = lambda self: f'{self} say hello!'
- return cls
- @add_hello
- class Person:
- def __init__(self, name):
- self.name = name
- def __str__(self):
- return self.name
- def test_3():
- p = Person('Ivan')
- print(p.hello())
- #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- def init_card_old(cls):
- cls.total = 0
- cls.type_card = 'debit'
- return cls
- @init_card_old
- class BankAccount:
- pass
- def test_4():
- print(BankAccount.total)
- print(BankAccount.type_card)
- #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- def init_card(total=0, type_card='debit'):
- def decorator(cls):
- cls.total = total
- cls.type_card = type_card
- return cls
- return decorator
- @init_card(total=100, type_card='credit')
- class BankAccount:
- pass
- @init_card(total=5005)
- class TimeDeposit:
- pass
- def test_5():
- print(TimeDeposit.total, TimeDeposit.type_card)
- print(BankAccount.total, BankAccount.type_card)
- def main():
- # test_2()
- # test_3()
- # test_4()
- test_5()
- if __name__ == '__main__':
- main()
|