TelenkovDmitry před 6 měsíci
rodič
revize
d7c9201fb9

+ 92 - 0
courses/python_oop/descriptor/data_desc_1.py

@@ -0,0 +1,92 @@
+
+class CoordinateValue:
+    def __init__(self, name):
+        self.storage_name = '_' + name
+
+    def __set__(self, instance, value):
+        setattr(instance, self.storage_name, int(value))
+
+    def __get__(self, instance, owner_class):
+        '''
+        if instance is None:
+            print('__get__ called from class')
+        else:
+            print(f'__get__ called, instance={instance}, owner_class={owner_class}')
+        '''
+        if instance is None:
+            return self
+        return getattr(instance, self.storage_name, None)
+
+
+
+class Point:
+    x = CoordinateValue('x')
+    y = CoordinateValue('y')
+    
+def test_point():
+    p1 = Point()
+    p1.x = 100
+    p1.y = 5
+    print(p1.x, p1.y)
+    print(p1.__dict__)
+
+    p2 = Point()
+    p2.x = 2
+    p2.y = 3
+    print(p2.x, p2.y)
+    print(p2.__dict__)
+
+#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# __set_name__
+# Метод срабатывает в процессе создания класса и все!
+
+
+class StringValidation:
+    def __init__(self, min_length):
+        self.min_length = min_length
+
+    def __set_name__(self, owner, name):
+        print(f'__set_name__ called: owner={owner}, attr_name={name}')
+        self.attribute_name = name
+
+    def __get__(self, instance, owner_class):
+        if instance is None:
+            return self
+        else:
+            print(f'calling __get__ for {self.attribute_name}')
+            return instance.__dict__.get(self.attribute_name, None)
+            # key = '_' + self.attribute_name
+            # return getattr(instance, key, None)
+
+
+    def __set__(self, instance, value):
+        if not isinstance(value, str):
+            raise ValueError(f'В атрибут {self.attribute_name} можно \
+                             сохранять только строки.')
+        if len(value) < self.min_length:
+            raise ValueError(f'Длина атрибута {self.attribute_name} должна \
+                             быть не меньше {self.min_length} символов')
+        key = '_' + self.attribute_name
+        # setattr(instance, key, value)
+        instance.__dict__[self.attribute_name] = value
+
+
+
+class Person:
+    name = StringValidation(5)
+    last_name = StringValidation(7)
+
+
+def main():
+    p = Person()
+    p.name = 'Michail'
+    p.last_name = 'Lermontov'
+    print(p.name, p.last_name)
+    try:
+        p.name = 'M.'
+    except ValueError as ex:
+        print(ex)
+    print(p.name, p.last_name)
+
+if __name__ == '__main__':
+    main()

+ 67 - 0
courses/python_oop/descriptor/ex_1.py

@@ -0,0 +1,67 @@
+
+class ColourComponent:
+    def __init__(self, start, end):
+        self.start = start
+        self.end = end
+
+    def __get__(self, instance, owner_class):
+        # print(f'__get__ called')
+        return int(instance.hex[self.start:self.end], 16)
+
+    def __set__(self, instance, value):
+        # print('__set__ called')
+        pass
+
+class Colour:
+    r = ColourComponent(1, 3)
+    g = ColourComponent(3, 5)
+    b = ColourComponent(5, 7)
+
+    def __init__(self, hex):
+        self.hex = hex
+
+def test_colour():
+    colour = Colour('#ff8823')
+    print(colour.r)
+    print(colour.g)
+    print(colour.b)
+
+
+#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+class MaxLengthAttribute:
+
+    def __get__(self, instance, owner_class):
+        if instance.__dict__ == {}:
+            return None
+        return sorted(instance.__dict__.keys(), key= lambda x: (len(x), x), reverse=True)[0]
+
+
+
+
+class MyClass:
+    max_length_attribute = MaxLengthAttribute()
+
+class JustClass:
+    max_atr = MaxLengthAttribute()
+
+
+def test_len():
+
+    # obj = MyClass()
+    # obj.name = "Vasiliy"
+    # obj.city = "Saint Peterburg"
+    # obj.country = "Rus"
+    # print(obj.max_length_attribute)
+
+    obj = JustClass()
+    obj.mock = 15
+    obj.city = "Saint Peterburg"
+    obj.name = "Vasiliy"
+    obj.door = 'wood'
+    print(obj.max_atr)
+
+
+if __name__ == '__main__':
+    # test_colour()
+    test_len()

+ 0 - 0
courses/python_oop/descriptor/ex_2.py


+ 50 - 0
courses/python_oop/descriptor/no_data_desc_1.py

@@ -0,0 +1,50 @@
+
+import time
+from datetime import datetime
+
+
+class Time:
+    def __get__(self, instance, owner_class):
+        print('get access to __get__ method')
+        print(f'self = {self}')
+        print(f'instance = {instance}')
+        print(f'owner_class = {owner_class}')
+        return datetime.now().isoformat()
+
+'''
+class Time:
+    
+    def __get__(self, instance, owner_class):
+        if instance is None:
+            return self
+        else:
+            return datetime.now().isoformat()
+    
+    # Тоже, но через свойства
+   
+    # @property
+    # def current_time(self):
+    #     return datetime.now().isoformat()
+   
+'''
+            
+class Logger:
+    current_time = Time()
+
+    # Есил current_time = @property
+    # current_time = Time().current_time
+
+
+def main():
+    # log = Logger()
+    # print(log.current_time)
+    # time.sleep(2)
+    # print(log.current_time)
+
+    print(Logger.current_time)
+    # log = Logger()
+    # print(log.current_time)
+
+
+if __name__ == '__main__':
+    main()