class_dec_1.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. '''Декорирование классов'''
  2. '''Обычный декоратор'''
  3. from functools import wraps
  4. def header_h1(func):
  5. @wraps(func)
  6. def inner(*args, **kwargs):
  7. result = func(*args, **kwargs)
  8. return f'<h1>{result}</h1>'
  9. return inner
  10. def header_h2(func):
  11. def wrapper(*args, **kwargs):
  12. result = func(*args, **kwargs)
  13. return f'<h2>{result}<h2>'
  14. return wrapper
  15. @header_h2
  16. def say_hello_to(name, surname):
  17. return f'Hello {name} {surname}'
  18. def test_1():
  19. res = say_hello_to('Vasya', 'Ivanov')
  20. print(f'{res=}')
  21. '''Создание атрибутов в классе при помощи декоратора'''
  22. '''
  23. def custom_settings(cls):
  24. cls.host = '127.0.0.1'
  25. cls.port = 80
  26. return cls
  27. '''
  28. def custom_settings(host='127.0.0.1', port=10):
  29. def decorator(cls):
  30. cls.host = host
  31. cls.port = port
  32. return cls
  33. return decorator
  34. @custom_settings(port=99)
  35. class Settings:
  36. pass
  37. @custom_settings(host='10.32.2.43', port=19)
  38. class Settings2:
  39. pass
  40. def test_2():
  41. print(Settings.host, Settings.port)
  42. print(Settings2.host, Settings2.port)
  43. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  44. '''Создание методов в классе при помощи декоратора'''
  45. def add_hello(cls):
  46. cls.hello = lambda self: f'{self} say hello!'
  47. return cls
  48. @add_hello
  49. class Person:
  50. def __init__(self, name):
  51. self.name = name
  52. def __str__(self):
  53. return self.name
  54. def test_3():
  55. p = Person('Ivan')
  56. print(p.hello())
  57. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  58. def init_card_old(cls):
  59. cls.total = 0
  60. cls.type_card = 'debit'
  61. return cls
  62. @init_card_old
  63. class BankAccount:
  64. pass
  65. def test_4():
  66. print(BankAccount.total)
  67. print(BankAccount.type_card)
  68. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  69. def init_card(total=0, type_card='debit'):
  70. def decorator(cls):
  71. cls.total = total
  72. cls.type_card = type_card
  73. return cls
  74. return decorator
  75. @init_card(total=100, type_card='credit')
  76. class BankAccount:
  77. pass
  78. @init_card(total=5005)
  79. class TimeDeposit:
  80. pass
  81. def test_5():
  82. print(TimeDeposit.total, TimeDeposit.type_card)
  83. print(BankAccount.total, BankAccount.type_card)
  84. def main():
  85. # test_2()
  86. # test_3()
  87. # test_4()
  88. test_5()
  89. if __name__ == '__main__':
  90. main()