classmethod.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. #classmethod staticmethod
  2. import json
  3. class Example:
  4. def hello():
  5. print('hello')
  6. '''Не привязывается ни к экземпляру ни к классу.
  7. Не имеет доступа к self и не может его изменить.'''
  8. @staticmethod
  9. def static_hello():
  10. print('static hello')
  11. '''Принимае объект самого класса.
  12. Может создавать новые экземпляры класса.'''
  13. @classmethod
  14. def class_hello(cls):
  15. print(f'class hello {cls}')
  16. class TemperatureConverter:
  17. @staticmethod
  18. def celsius_to_fahrenheit(val):
  19. return val*9/5 + 32
  20. @staticmethod
  21. def fahrenheit_to_celsius(val):
  22. return (val - 32)*5/9
  23. @staticmethod
  24. def celsius_to_kelvin(val):
  25. return val + 273.15
  26. @staticmethod
  27. def kelvin_to_celsius(val):
  28. return val - 273.15
  29. @staticmethod
  30. def fahrenheit_to_kelvin(val):
  31. return round(((val - 32)*5/9 + 273.15), 2)
  32. @staticmethod
  33. def kelvin_to_fahrenheit(val):
  34. return round(((val - 273.15)*9/5 + 32), 2)
  35. @staticmethod
  36. def format(val, sim: str):
  37. return f"{val}°{sim}"
  38. class Circle:
  39. def __init__(self, radius):
  40. if not Circle.is_positive(radius):
  41. raise ValueError("Радиус должен быть положительным")
  42. self.radius = radius
  43. @classmethod
  44. def from_diameter(cls, value):
  45. return cls(value/2.0)
  46. @staticmethod
  47. def is_positive(value):
  48. return True if value >= 0 else False
  49. @staticmethod
  50. def area(radius):
  51. return 3.14*radius**2
  52. class AppConfig:
  53. __config = {}
  54. def __init__(self):
  55. pass
  56. @classmethod
  57. def load_config(cls, file_name: str):
  58. with open(file_name, "r") as f:
  59. cls.__config = json.load(f)
  60. @classmethod
  61. def get_config(cls, key : str):
  62. if '.' in key:
  63. external_key, internal_key = key.split('.')
  64. if external_key in cls.__config.keys() and internal_key in cls.__config[external_key].keys():
  65. return cls.__config[external_key][internal_key]
  66. else:
  67. return None
  68. else:
  69. if key in cls.__config.keys():
  70. return cls.__config[key]
  71. else:
  72. return None
  73. def main():
  74. AppConfig.load_config('app_config.json')
  75. # Получение значения конфигурации
  76. assert AppConfig.get_config('database') == {
  77. 'host': '127.0.0.1', 'port': 5432,
  78. 'database_name': 'postgres_db',
  79. 'user': 'owner',
  80. 'password': 'ya_vorona_ya_vorona'}
  81. assert AppConfig.get_config('database.user') == 'owner'
  82. assert AppConfig.get_config('database.password') == 'ya_vorona_ya_vorona'
  83. assert AppConfig.get_config('database.pass') is None
  84. assert AppConfig.get_config('password.database') is None
  85. config = AppConfig()
  86. assert config.get_config('max_connections') == 10
  87. assert config.get_config('min_connections') is None
  88. conf = AppConfig()
  89. assert conf.get_config('max_connections') == 10
  90. assert conf.get_config('database.user') == 'owner'
  91. assert conf.get_config('database.host') == '127.0.0.1'
  92. assert conf.get_config('host') is None
  93. print('Good')
  94. if __name__ == '__main__':
  95. main()