TelenkovDmitry 8 tháng trước cách đây
mục cha
commit
ff84b75f28

+ 12 - 0
courses/python_oop/app_config.json

@@ -0,0 +1,12 @@
+{
+    "database": {
+      "host": "127.0.0.1",
+      "port": 5432,
+      "database_name": "postgres_db",
+      "user": "owner",
+      "password": "ya_vorona_ya_vorona"
+    },
+    "api_key": "hUFHu834837248jhoiHF89",
+    "log_level": "debug",
+    "max_connections": 10
+}

+ 129 - 0
courses/python_oop/classmethod.py

@@ -0,0 +1,129 @@
+#classmethod staticmethod
+
+import json
+
+class Example:
+    def hello():
+        print('hello')
+
+    '''Не привязывается ни к экземпляру ни к классу.
+    Не имеет доступа к self и не может его изменить.'''
+    @staticmethod
+    def static_hello():
+        print('static hello')
+
+    '''Принимае объект самого класса.
+    Может создавать новые экземпляры класса.'''
+    @classmethod
+    def class_hello(cls):
+        print(f'class hello {cls}')
+
+
+class TemperatureConverter:
+
+    @staticmethod
+    def celsius_to_fahrenheit(val):
+        return val*9/5 + 32
+
+    @staticmethod
+    def fahrenheit_to_celsius(val):
+        return (val - 32)*5/9
+
+    @staticmethod
+    def celsius_to_kelvin(val):
+        return val + 273.15
+
+    @staticmethod
+    def kelvin_to_celsius(val):
+        return val - 273.15
+
+    @staticmethod
+    def fahrenheit_to_kelvin(val):
+        return round(((val - 32)*5/9 + 273.15), 2)
+
+    @staticmethod
+    def kelvin_to_fahrenheit(val):
+        return round(((val - 273.15)*9/5 + 32), 2)
+
+    @staticmethod
+    def format(val, sim: str):
+        return f"{val}°{sim}"
+
+
+class Circle:
+
+    def __init__(self, radius):
+        if not Circle.is_positive(radius):
+            raise ValueError("Радиус должен быть положительным")
+        self.radius = radius
+
+    @classmethod
+    def from_diameter(cls, value):
+        return cls(value/2.0)
+
+    @staticmethod
+    def is_positive(value):
+        return True if value >= 0 else False
+
+    @staticmethod
+    def area(radius):
+        return 3.14*radius**2
+
+
+class AppConfig:
+
+    __config = {}
+
+    def __init__(self):
+        pass
+
+    @classmethod
+    def load_config(cls, file_name: str):
+        with open(file_name, "r") as f:
+            cls.__config = json.load(f)
+            
+    @classmethod
+    def get_config(cls, key : str):
+
+        if '.' in key:
+            external_key, internal_key = key.split('.')
+            if external_key in cls.__config.keys() and internal_key in cls.__config[external_key].keys():
+                return cls.__config[external_key][internal_key]
+            else:
+                return None
+        else:
+            if key in cls.__config.keys():
+                return cls.__config[key]
+            else:
+                return None
+
+
+def main():
+
+    AppConfig.load_config('app_config.json')
+
+    # Получение значения конфигурации
+    assert AppConfig.get_config('database') == {
+        'host': '127.0.0.1', 'port': 5432,
+        'database_name': 'postgres_db',
+        'user': 'owner',
+        'password': 'ya_vorona_ya_vorona'}
+    assert AppConfig.get_config('database.user') == 'owner'
+    assert AppConfig.get_config('database.password') == 'ya_vorona_ya_vorona'
+    assert AppConfig.get_config('database.pass') is None
+    assert AppConfig.get_config('password.database') is None
+
+    config = AppConfig()
+    assert config.get_config('max_connections') == 10
+    assert config.get_config('min_connections') is None
+
+    conf = AppConfig()
+    assert conf.get_config('max_connections') == 10
+    assert conf.get_config('database.user') == 'owner'
+    assert conf.get_config('database.host') == '127.0.0.1'
+    assert conf.get_config('host') is None
+
+    print('Good')
+
+if __name__ == '__main__':
+    main()

+ 117 - 1
courses/python_oop/dec.py

@@ -139,7 +139,7 @@ class Money:
     def cents(self, value):
         if not isinstance(value, (int)): 
             print("Error cents")
-        elif  value < 0 or value > 100:
+        elif  value < 0 or value >= 100:
             print("Error cents")
         else:
             self.total_cents = (self.total_cents//100)*100 + value
@@ -148,13 +148,127 @@ class Money:
         return f"Ваше состояние составляет {self.total_cents//100} долларов {self.total_cents%100} центов"
 
 
+"""Вычисляемые войства"""
+
+class Square:
+    def __init__(self, a) -> None:
+        self.__side = a
+        self.__area = None
+        self.__perimeter = None
+
+    @property
+    def side(self):
+        return self.__side
+
+    @side.setter
+    def side(self, value):
+        self.__side = value
+        self.__area = None
+        self.__perimeter = None
+
+    @property
+    def area(self):
+        if self.__area == None:
+            print('calculate area')
+            self.__area = self.__side**2
+        return self.__area
+
+    @property
+    def perimeter(self):
+        if self.__perimeter == None:
+            print('calculate perimeter')
+            self.__perimeter = self.__side*4
+        return self.__perimeter
+
+
+class Rectangle:
+    def __init__(self, length, width):
+        self.__length = length
+        self.__width = width
+        self.__area = None
+
+    @property
+    def area(self):
+        if self.__area == None:
+            self.__area = self.__length*self.__width
+        return self.__area
+
+    
+class Date:
+
+    def __init__(self, day, month, year) -> None:
+        self.day = day
+        self.month = month
+        self.year = year
+
+    @property
+    def date(self):
+        return "%02d/%02d/%04d" % (self.day, self.month, self.year)
+
+    @property
+    def usa_date(self):
+        return "%02d-%02d-%04d" % (self.month, self.day, self.year)
+
+
+class Password:
+
+    def __init__(self, password) -> None:
+        self.__password = password
+
+    @property
+    def password(self):
+        return self.__password
+
+    @password.setter
+    def password(self, value):
+        self.__password = value
+
+    @property
+    def strength(self):
+        if len(self.password) < 8:
+            return "Weak"
+        elif len(self.password) >= 12:
+            return "Strong"
+        else:
+            return "Medium"
+
+
 def main():
+
+    pass_1 = Password("Alligator34")
+    assert pass_1.password == "Alligator34"
+    assert pass_1.strength == "Medium"  
+    assert len(pass_1.__dict__) == 1, 'У ЭК должен храниться только один атрибут'
+
+    pass_2 = Password("Alligator345678")
+    assert pass_2.password == "Alligator345678"
+    assert pass_2.strength == "Strong"
+    pass_1.password = "123"
+    assert pass_1.strength == "Weak"
+    assert len(pass_2.__dict__) == 1, 'У ЭК должен храниться только один атрибут'
+
+    pass_3 = Password("345678")
+    assert pass_3.strength == "Weak"
+    print('Good')
+    assert len(pass_3.__dict__) == 1, 'У ЭК должен храниться только один атрибут'
+
     # acc = BankAccount('Ivan', 200)
     # print(acc.my_balance)
 
+    '''
+    date = Date(3, 4, 2001)
+    print(date.date)
+    print(date.usa_date)
+    '''
+
+    # one_dollar = 1
+    # print(f"{one_dollar:05}")
+
     '''
     note = Notebook(['Buy Potato', 'Buy Carrot', 'Wash car'])
     note.notes_list
+    '''
+
     '''
     bill = Money(101, 99)
     assert isinstance(bill, Money)
@@ -186,6 +300,8 @@ def main():
     ken.cents = 100  # Error cents
     ken.cents = 99
     print(ken)
+    '''
+
 
     '''
     box = MagicBox("rubies")

+ 0 - 0
courses/python_oop/tanya.py