TelenkovDmitry 6 ماه پیش
والد
کامیت
624efdf504

+ 67 - 0
courses/python_oop/exception/exception_1.py

@@ -0,0 +1,67 @@
+
+class Wallet:
+
+    def __init__(self, currency, balance):
+
+        if not isinstance(currency, str):
+            raise TypeError("Неверный тип валюты")
+        elif len(currency) != 3:
+            raise NameError("Неверная длина названия валюты")
+        elif not currency.isupper():
+            raise ValueError("Название должно состоять только из заглавных букв")
+        self.currency = currency
+        self.balance = balance
+
+    def __eq__(self, value):
+        if not isinstance(value, Wallet):
+            raise TypeError(f"Wallet не поддерживает сравнение с {value}")
+        elif self.currency != value.currency:
+            raise ValueError("Нельзя сравнить разные валюты")
+        else:
+            return self.balance == value.balance
+        
+    def __add__(self, value):
+        if not isinstance(value, Wallet):
+            raise ValueError("Данная операция запрещена")
+        elif self.currency != value.currency:
+            raise ValueError("Данная операция запрещена")
+        else:
+            return Wallet(self.currency, self.balance + value.balance)
+
+    def __sub__(self, value):
+        if not isinstance(value, (Wallet)):
+            raise ValueError("Данная операция запрещена")
+        elif self.currency != value.currency:
+            raise ValueError("Данная операция запрещена")
+        else:
+            return Wallet(self.currency, self.balance - value.balance)
+
+
+def main():
+
+    '''
+    wallet1 = Wallet('USD', 50)
+    wallet2 = Wallet('RUB', 100)
+    wallet3 = Wallet('RUB', 150)
+    wallet4 = Wallet(12, 150)  # исключение TypeError('Неверный тип валюты')
+    wallet5 = Wallet('qwerty', 150)  # исключение NameError('Неверная длина названия валюты')
+    wallet6 = Wallet('abc', 150)  # исключение ValueError('Название должно состоять только из заглавных букв')
+    print(wallet2 == wallet3)  # False
+    print(wallet2 == 100)  # TypeError('Wallet не поддерживает сравнение с 100')
+    print(wallet2 == wallet1)  # ValueError('Нельзя сравнить разные валюты')
+    wallet7 = wallet2 + wallet3
+    print(wallet7.currency, wallet7.balance)  # печатает 'RUB 250'
+    wallet2 + 45  # ValueError('Данная операция запрещена')
+    '''
+
+    '''
+    try:
+        int('sdfawsdf')
+    except ValueError:
+        print('!!!!')
+    '''
+
+
+
+if __name__ == '__main__':
+    main()

+ 34 - 2
courses/python_oop/inheritance/slots.py

@@ -1,3 +1,4 @@
+from timeit import timeit
 
 class Point:
 
@@ -15,9 +16,40 @@ class PointSlots:
         self.x = x
         self.y = y
 
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+class Person:
+
+    __slots__ = {'first_name', 'last_name', 'age'}
+
+    def __init__(self, first_name, last_name, age):
+        self.first_name = first_name
+        self.last_name = last_name
+        self.age = age
+
+    def __str__(self):
+        return f"{self.first_name} {self.last_name} is {self.age} years old"
+
+
+def make_cl1():
+    s = Point(3, 4)
+    s.x = 100
+    s.x
+    del s.x
+
+def make_cl2():
+    s = PointSlots(3, 4)
+    s.x = 100
+    s.x
+    del s.x
+
+
+
 
 def main():
-    pass
-    
+    print(timeit(make_cl1))
+    print(timeit(make_cl2))
+
+
 if __name__ == '__main__':
     main()

+ 49 - 0
courses/python_oop/inheritance/slots_2.py

@@ -0,0 +1,49 @@
+
+class Rectangle:
+
+    __slots__ = '__width', 'height'
+
+    def __init__(self, a, b):
+        self.width = a
+        self.height = b
+
+    @property
+    def width(self):
+        return self.__width
+    
+    @width.setter
+    def width(self, value):
+        print("Setter called")
+        self.__width = value
+
+    @property
+    def perimetr(self):
+        return (self.height + self.width) * 2
+
+    @property
+    def area(self):
+        return self.height * self.width
+
+# У класса наследника будет атрибут __dict__ если не задать атрибут __slots__
+class Square(Rectangle):
+    
+    # этот slots расширяет имена родительского класса
+    __slots__ = 'color'
+
+    def __init__(self, a, b, color):
+        super().__init__(a, b)
+        self.color = color
+
+
+def main():
+    a = Rectangle(3, 4)
+    b = Rectangle(5, 6)
+
+    print(b.perimetr, b.area)
+
+
+    s = Square(3, 6, 'red')
+    # print(s.__dict__)
+
+if __name__ == '__main__':
+    main()

+ 155 - 0
courses/python_oop/inheritance/slots_3.py

@@ -0,0 +1,155 @@
+
+class Device:
+
+    __slots__ = '_name', '_location', '_status'
+
+    def __init__(self, name, location, status='ON'):
+        self._name = name
+        self.location = location
+        self.status = status
+    
+    @property
+    def name(self):
+        return self._name
+
+    @property
+    def location(self):
+        return self._location
+    
+    @location.setter
+    def location(self, value):
+        self._location = value
+    
+    @property
+    def status(self):
+        return self._status
+    
+    @status.setter
+    def status(self, value):
+        self._status = value
+
+    def turn_on(self):
+        self.status = 'ON'
+
+    def turn_off(self):
+        self.status = 'OFF'
+
+class Light(Device):
+
+    __slots__ = '_brightness', '_color'
+
+    def __init__(self, name, location, brightness, color):
+        super().__init__(name, location)
+        self.brightness = brightness
+        self._color = color
+        
+    @property
+    def brightness(self):
+        return self._brightness
+    
+    @brightness.setter
+    def brightness(self, value):
+        self._brightness = value
+    
+    @property
+    def color(self):
+        return self._color
+
+
+class Thermostat(Device):
+
+    __slots__ = '_current_temperature', '_target_temperature'
+
+    def __init__(self, name, location, current_temperature, target_temperature):
+        super().__init__(name, location)
+        self.current_temperature = current_temperature
+        self.target_temperature = target_temperature
+
+    @property
+    def current_temperature(self):
+        return self._current_temperature
+    
+    @current_temperature.setter
+    def current_temperature(self, value):
+        self._current_temperature = value
+
+    @property
+    def target_temperature(self):
+        return self._target_temperature
+    
+    @target_temperature.setter
+    def target_temperature(self, value):
+        self._target_temperature = value
+
+
+class SmartTV(Device):
+
+    __slots__ = '_channel'
+
+    def __init__(self, name, location, channel):
+        super().__init__(name, location)
+        self.channel = channel
+
+    @property
+    def channel(self):
+        return self._channel
+    
+    @channel.setter
+    def channel(self, value):
+        self._channel = value
+
+def main():
+
+    '''
+    dev = Device('robot-bobot', 'Moscow', 'on')
+    print(dev.name)
+
+    light = Light('light-bobot', 'Moscow', 'on', 70, 'red')
+    print(light.name)
+    print(light.brightness)
+    print(light.color)
+    '''
+
+    device1 = Device('Устройство 1', 'Гостиная')
+    assert device1.name == 'Устройство 1'
+    assert device1._name == 'Устройство 1'
+    assert device1.location == 'Гостиная'
+    assert device1._location == 'Гостиная'
+    assert device1.status == 'ON'
+    assert device1._status == 'ON'
+
+    device1.turn_off()
+    assert device1.status == 'OFF'
+    device1.location = 'Кухня'
+    assert device1.location == 'Кухня'
+    assert device1._location == 'Кухня'
+    device1.turn_on()
+    assert device1.status == 'ON'
+
+    light1 = Light('Лампа', 'Гостиная', 50, 'белый')
+    light1.name == 'Лампа'
+    light1.location == 'Гостиная'
+    light1.status == 'ON'
+    light1.brightness == '50'
+    light1.color == 'белый'
+
+    light1.turn_off()
+    light1.status == 'OFF'
+
+    thermostat_1 = Thermostat('Термометр', 'Балкон', 10, 15)
+    thermostat_1.name == 'Термометр'
+    thermostat_1.location == 'Балкон'
+    thermostat_1.status == 'ON'
+    thermostat_1.current_temperature == 10
+    thermostat_1.target_temperature == 15
+
+    tv = SmartTV('Samsung', 'Спальня', 20)
+    tv.name == 'Термометр'
+    tv.location == 'Балкон'
+    tv.status == 'ON'
+    tv.channel == 20
+
+    print('GOOD')
+
+if __name__ == '__main__':
+    main()