TelenkovDmitry 8 meses atrás
pai
commit
2fb5dc0ae5

+ 210 - 0
courses/python_oop/method.py

@@ -0,0 +1,210 @@
+import math
+
+class Cat:
+
+    breed = 'pers'
+
+    def hello():
+        print("hello")
+
+    def show_breed(instance):
+        print(f'my breed is {instance.breed}')
+        print(instance)
+
+    def show_name(instance):
+        if hasattr(instance, 'name'):
+            print(f'my name is {instance.name}')
+        else:
+            print('nothing')
+
+    def set_value(koshka, value, age=0):
+        koshka.name = value
+        koshka.age = age
+
+    def new_method(self):
+        pass
+
+class Point:
+
+    list_points = []
+
+    def __init__(self, x, y) -> None:
+        self.move_to(x, y)
+        Point.list_points.append(self)
+
+    def move_to(self, x, y):
+        self.x = x
+        self.y = y
+
+    def go_home(self):
+        self.move_to(0, 0)
+
+    def print_point(self):
+        print(f"Точка с координатами ({self.x}, {self.y})")
+
+    def calc_distance(self, another_point):
+        if not isinstance(another_point, Point):
+            raise ValueError("Аргумент должен принадлежать классу Точка")
+        return math.sqrt((self.x - another_point.x)**2 + (self.y -another_point.y)**2)
+
+class Numbers:
+
+    def __init__(self, *args) -> None:
+        self.values = []
+        self.values.extend(args)
+
+    def add_number(self, val):
+        self.values.append(val)
+
+    def get_positive(self):
+        return [x for x in self.values if x > 0]
+
+    def get_negative(self):
+        return [x for x in self.values if x < 0]
+
+    def get_zeroes(self):
+        return [x for x in self.values if x == 0]
+
+
+class Stack:
+    def __init__(self):
+        self.values = []
+
+    def push(self, value):
+        self.values.append(value)
+
+    def pop(self):
+        if not self.values:
+            print("Empty Stack")
+        else:
+            return self.values.pop()
+
+    def peek(self):
+        if not self.values:
+            print("Empty Stack")
+            return None
+        return self.values[-1]
+    
+    def is_empty(self):
+        return not bool(self.values)
+
+    def size(self):
+        return len(self.values)
+
+class Worker:
+    def __init__(self, name, salary, gender, passport):
+        self.name = name
+        self.salary = salary
+        self.gender = gender
+        self.passport = passport
+
+    def get_info(self):
+        print(f"Worker {self.name}; passport-{self.passport}")
+
+
+class CustomLabel:
+    def __init__(self, text, **kw):
+        self.text = text
+        for name, value in kw.items():
+            setattr(self, name, value)
+
+    def config(self, **kw):
+        for name, value in kw.items():
+            setattr(self, name, value)
+        
+
+
+def main():
+
+    """CustomLabel"""
+    label1 = CustomLabel(text="Hello Python", fg="#eee", bg="#333")
+    label2 = CustomLabel(text="Username")
+    label3 = CustomLabel(text="Password", font=("Comic Sans MS", 24, "bold"), bd=20, bg='#ffaaaa')
+    label4 = CustomLabel(text="Hello", bd=20, bg='#ffaaaa')
+    label5 = CustomLabel(text="qwwerty", a=20, b='#ffaaaa', r=[3, 4, 5, 6], p=32)
+
+    assert label1.__dict__ == {'text': 'Hello Python', 'fg': '#eee', 'bg': '#333'}
+    assert label2.__dict__ == {'text': 'Username'}
+    assert label3.__dict__ == {'text': 'Password', 'font': ('Comic Sans MS', 24, 'bold'), 'bd': 20, 'bg': '#ffaaaa'}
+    assert label4.__dict__ == {'text': 'Hello', 'bd': 20, 'bg': '#ffaaaa'}
+    assert label5.__dict__ == {'text': 'qwwerty', 'a': 20, 'b': '#ffaaaa', 'r': [3, 4, 5, 6], 'p': 32}
+
+    print(label1.__dict__)
+    print(label2.__dict__)
+    print(label3.__dict__)
+    print(label4.__dict__)
+    print(label5.__dict__)
+
+    label4.config(color='red', bd=100)
+    label5.config(color='red', bd=100, a=32, b=432, p=100, z=432)
+
+    assert label4.__dict__ == {'text': 'Hello', 'bd': 100, 'bg': '#ffaaaa', 'color': 'red'}
+    assert label5.__dict__ == {'text': 'qwwerty', 'a': 32, 'b': 432, 'r': [3, 4, 5, 6], 'p': 100,
+                                'color': 'red', 'bd': 100, 'z': 432}
+
+    """Class Numbers"""
+    '''
+    num = Numbers(1, 2, -3, -4, 5)
+    num.get_values()
+    print(num.get_positive())
+    '''
+
+    """Class Stack"""
+    # stack = Stack()
+    # stack.peek()
+    # print(stack.is_empty())
+    
+    """Worker"""
+    """
+    persons= [
+    ('Allison Hill', 334053, 'M', '1635644202'),
+    ('Megan Mcclain', 191161, 'F', '2101101595'),
+    ('Brandon Hall', 731262, 'M', '6054749119'), 
+    ('Michelle Miles', 539898, 'M', '1355368461'),
+    ('Donald Booth', 895667, 'M', '7736670978'), 
+    ('Gina Moore', 900581, 'F', '7018476624'),
+    ('James Howard', 460663, 'F', '5461900982'), 
+    ('Monica Herrera', 496922, 'M', '2955495768'),
+    ('Sandra Montgomery', 479201, 'M', '5111859731'), 
+    ('Amber Perez', 403445, 'M', '0602870126')
+    ]
+
+
+    # workers_objects = [Worker('Bob Moore', 330000, 'M', '1635777202')]
+    
+    workers_objects = [Worker(*x) for x in persons]
+    
+    for worker in workers_objects:
+        worker.get_info()
+    """
+
+
+  
+
+
+
+
+    # print(persons[0][1])
+
+    # for person in persons:
+    #     workers_objects.append('')
+    
+    # cat = Cat()
+    # cat.show_breed()
+
+    # tom = Cat()
+    # print(isinstance(tom, Cat))
+
+    # tom.show_name()
+    # tom.set_value('Tom')
+    # tom.show_name()
+
+    # leo.score(700)
+    # assert leo.goals == 700
+    # leo.make_assist(500)
+    # assert leo.assists == 500
+
+    # leo.statistics()
+
+if __name__ == '__main__':
+    main()

+ 33 - 0
courses/python_oop/patterns/monostate.py

@@ -0,0 +1,33 @@
+
+class WeatherStation:
+    __shared_data = {"temperature": 0,
+                     "humidity": 0,
+                     "pressure": 0}
+    
+    def __init__(self):
+        self.__dict__ = WeatherStation.__shared_data
+
+    def update_data(self, temp, hum, pres):
+        self.__shared_data['temperature'] = temp
+        self.__shared_data['humidity'] = hum
+        self.__shared_data['pressure'] = pres
+
+    def get_current_data(self):
+        return (self.__shared_data['temperature'], self.__shared_data['humidity'], self.__shared_data['pressure'])
+
+
+sensor1 = WeatherStation()
+assert sensor1.temperature == 0
+assert sensor1.humidity == 0
+assert sensor1.pressure == 0
+sensor2 = WeatherStation()
+assert sensor2.get_current_data() == (0, 0, 0)
+sensor1.update_data(25, 60, 103)
+assert sensor1.get_current_data() == (25, 60, 103)
+assert sensor2.get_current_data() == (25, 60, 103)
+sensor3 = WeatherStation()
+assert sensor3.get_current_data() == (25, 60, 103)
+sensor3.update_data(50, 20, 10)
+assert sensor1.get_current_data() == (50, 20, 10)
+assert sensor2.get_current_data() == (50, 20, 10)
+print('Good')

+ 158 - 0
courses/python_oop/private.py

@@ -0,0 +1,158 @@
+
+class BankAccount:
+
+    def __init__(self, name, balance, passport) -> None:
+        self._name = name
+        self._balance = balance
+        self._passport = passport
+
+        self.__name = name
+        self.__balance = balance
+        self.__passport = passport
+
+
+    def print_protected_data(self):
+        print(self._name, self._balance, self._passport)
+
+    # Инкапсуляция - сокрытие данных
+    def print_private_data(self):
+        print(self.__name, self.__balance, self.__passport)
+
+    def __private_method(self):
+        pass
+
+class Student:
+    def __init__(self, name, age, branch) -> None:
+        self.__name = name
+        self.__age = age
+        self.__branch = branch
+
+    def __display_details(self):
+        print(f'Имя: {self.__name}\n Возраст: {self.__age}\n Направление: {self.__branch}')
+
+    def access_private_method(self):
+        self.__display_details()
+
+
+class BankDeposit:
+    def __init__(self, name, balance, rate):
+        self.name = name
+        self.balance = balance
+        self.rate = rate
+
+    def __calculate_profit(self):
+        return self.balance/100*self.rate
+    
+    def get_balance_with_profit(self):
+        return self.balance + self.__calculate_profit()
+        
+
+class Library:
+    def __init__(self, books: list) -> None:
+        self.__books = books
+
+    def __check_availability(self, book_name):
+        return True if book_name in self.__books else False
+
+    def search_book(self, book_name):
+        return self.__check_availability(book_name)
+    
+    def return_book(self, book_name):
+        self.__books.append(book_name)
+
+    def _checkout_book(self, book_name):
+        if self.__check_availability(book_name):
+            self.__books.remove(book_name)
+            return True
+        else:
+            return False
+        
+
+class Employee:
+    def __init__(self, name, position, hours_worked, hourly_rate):
+        self.name = name
+        self.__position = position
+        self.__hours_worked = hours_worked
+        self.__hourly_rate = hourly_rate
+
+    def __calculate_salary(self):
+        return self.__hours_worked*self.__hourly_rate
+    
+    def _set_position(self, position):
+        self.__position = position
+
+    def get_position(self):
+        return self.__position
+    
+    def get_salary(self):
+        return self.__calculate_salary()
+    
+    def get_employee_details(self):
+        return f"Name: {self.name}, Position: {self.__position}, Salary: {self.__calculate_salary()}"
+
+def main():
+    '''
+    account1 = BankAccount('Bob', 1000, 2312312312)
+    account1.print_protected_data()
+    account1.print_private_data()
+    print(dir(account1))
+
+    # Доступ к приватным атрибутам и методам
+    account1._BankAccount__name = 'sdfsasd'
+    print(account1._BankAccount__name)
+    '''
+    '''
+    account = BankDeposit("John Connor", 1000, 5)
+    assert account.name == "John Connor"
+    assert account.balance == 1000
+    assert account.rate == 5
+    assert account._BankDeposit__calculate_profit() == 50.0
+    assert account.get_balance_with_profit() == 1050.0
+
+    account_2 = BankDeposit("Sarah Connor", 200, 27)
+    assert account_2.name == "Sarah Connor"
+    assert account_2.balance == 200
+    assert account_2.rate == 27
+    assert account_2._BankDeposit__calculate_profit() == 54.0
+    assert account_2.get_balance_with_profit() == 254.0
+    print('Good')
+    '''
+
+    '''
+    library = Library(["War and Peace", "Moby-Dick", "Pride and Prejudice"])
+
+    assert library._Library__books == ["War and Peace", "Moby-Dick", "Pride and Prejudice"]
+    assert library.search_book("Moby-Dick") == True
+    assert library.search_book("Jane Air") == False
+
+    assert library._Library__check_availability("War and Peace") == True
+    assert library._checkout_book("Moby-Dick") == True
+    assert library._Library__books == ["War and Peace", "Pride and Prejudice"]
+
+    assert library.search_book("Moby-Dick") == False
+    assert library.return_book("Moby-Dick") is None
+    assert library._Library__books == ["War and Peace", "Pride and Prejudice", "Moby-Dick"]
+    assert library.search_book("Moby-Dick") == True
+    print('Good')
+    '''
+    employee = Employee("Джеки Чан", 'manager', 20, 40)
+    assert employee.name == 'Джеки Чан'
+    assert employee._Employee__hours_worked == 20
+    assert employee._Employee__hourly_rate == 40
+    assert employee._Employee__position == 'manager'
+    assert employee.get_position() == 'manager'
+    assert employee.get_salary() == 800
+    assert employee._Employee__calculate_salary() == 800
+    assert employee.get_employee_details() == 'Name: Джеки Чан, Position: manager, Salary: 800'
+    employee._set_position('Director')
+    assert employee.get_employee_details() == 'Name: Джеки Чан, Position: Director, Salary: 800'
+
+    employee_2 = Employee("Пирс Броснан", 'actor', 35, 30)
+    assert employee_2._Employee__calculate_salary() == 1050
+    assert employee_2.get_employee_details() == 'Name: Пирс Броснан, Position: actor, Salary: 1050'
+
+print('Good')
+
+
+if __name__ == '__main__':
+    main()

+ 176 - 0
courses/python_oop/property_method.py

@@ -0,0 +1,176 @@
+
+# Property. getter, setter.
+'''
+class BandAccount:
+    def __init__(self, name, balance) -> None:
+        self.name = name
+        self.__balance = balance
+        
+    def get_balance(self):
+        return self.__balance
+    
+    def set_balance(self, value):
+        if not isinstance(value, (int, float)):
+            raise ValueError("Баланс должен быть числом")
+        self.__balance = value
+'''
+
+'''
+class BankAccount:
+    def __init__(self, name, balance) -> None:
+        self.name = name
+        self.__balance = balance
+        
+    def get_balance(self):
+        return self.__balance
+    
+    def set_balance(self, value):
+        if not isinstance(value, (int, float)):
+            raise ValueError("Баланс должен быть числом")
+        self.__balance = value
+
+    def delete_balance(self):
+        del self.__balance
+
+    balance = property(fget=get_balance, fset=set_balance, fdel=delete_balance)
+'''
+
+class BankAccount:
+    def __init__(self, name, balance) -> None:
+        self.name = name
+        self.__balance = balance
+        
+    def get_balance(self):
+        return self.__balance
+    
+    def set_balance(self, value):
+        if not isinstance(value, (int, float)):
+            raise ValueError("Баланс должен быть числом")
+        self.__balance = value
+
+    def delete_balance(self):
+        del self.__balance
+
+    balance = property(fget=get_balance, fset=set_balance, fdel=delete_balance)
+    
+
+class BankAccount:
+    def __init__(self, account_number, balance) -> None:
+        self._account_number = account_number
+        self._balance = balance
+
+    def get_account_number(self):
+        return self._account_number
+    
+    def get_balance(self):
+        return self._balance
+    
+    def set_balance(self, value):
+        if not isinstance(value, (int, float)):
+            raise ValueError("ErrorValue!!!")
+        self._balance = value
+
+        
+class Employee:
+    def __init__(self, name, salary) -> None:
+        self.__name = name
+        self.__salary = salary
+
+    def __get_name(self):
+        return self.__name
+
+    def __get_salary(self):
+        return self.__salary
+    
+    def __set_salary(self, value):
+        if not isinstance(value, (int, float)) or (value < 0):
+            print(f"ErrorValue:{value}")
+            return
+        self.__salary = value
+
+    title = property(fget=__get_name)
+
+    reward = property(fget=__get_salary, fset=__set_salary)
+
+
+class UserMail:
+    def __init__(self, login, email: str):
+        self.login = login
+        self.__email = email
+
+    def get_email(self):
+        return self.__email
+    
+    def set_email(self, email):
+        if not isinstance(email, str):
+            print(f"ErrorMail:{email}")
+            return
+        if email.count('@') == 1 and (email.rfind('@') < email.rfind('.')):
+            self.__email = email
+        else:
+            print(f"ErrorMail:{email}")
+            return
+
+    email = property(fget=get_email, fset=set_email)
+
+
+
+
+def main():
+    '''
+    acc = BandAccount('Ivan', 200)
+    acc.balance = 400
+    print(acc.balance)
+    '''
+
+    '''
+    employee = Employee("John Doe", 50000)
+    assert employee.title == "John Doe"
+    assert employee._Employee__name == "John Doe"
+    assert isinstance(employee, Employee)
+    assert isinstance(type(employee).title, property), 'Вы не создали property title'
+    assert isinstance(type(employee).reward, property), 'Вы не создали property reward'
+
+    assert employee.reward == 50000
+    employee.reward = -100  # ErrorValue:-100
+
+    employee.reward = 1.5
+    assert employee.reward == 1.5
+
+    employee.reward = 70000
+    assert employee.reward == 70000
+    employee.reward = 'hello'  # Печатает ErrorValue:hello
+    employee.reward = '777'  # Печатает ErrorValue:777
+    employee.reward = [1, 2]  # Печатает ErrorValue:[1, 2]
+    assert employee.reward == 70000
+    employee._Employee__set_salary(55000)
+    assert employee._Employee__get_salary() == 55000
+    '''
+
+    jim = UserMail("aka47", 'hello@com.org')
+    assert jim.login == "aka47"
+    assert jim._UserMail__email == "hello@com.org"
+    assert isinstance(jim, UserMail)
+    assert isinstance(type(jim).email, property), 'Вы не создали property email'
+
+    jim.email = [1, 2, 3]  # печатает ErrorMail:[1, 2, 3]
+    jim.email = 'hello@@re.ee'  # печатает ErrorMail:hello@@re.ee
+    jim.email = 'hello@re.w3'
+    assert jim.email == 'hello@re.w3'
+
+    k = UserMail('belosnezhka', 'prince@wait.you')
+    assert k.email == 'prince@wait.you'
+    assert k.login == 'belosnezhka'
+    assert isinstance(k, UserMail)
+
+    k.email = {1, 2, 3}  # печатает ErrorMail:{1, 2, 3}
+    k.email = 'prince@still@.wait'  # печатает ErrorMail:prince@still@.wait
+    k.email = 'prince@stillwait'  # печатает ErrorMail:prince@stillwait
+    k.email = 'prince@still.wait'
+    assert k.get_email() == 'prince@still.wait'
+    k.email = 'pri.nce@stillwait'  # печатает ErrorMail:pri.nce@stillwait
+    assert k.email == 'prince@still.wait'
+
+
+if __name__ == '__main__':
+    main()

+ 84 - 2
courses/python_oop/task.py

@@ -1,3 +1,80 @@
+
+class Person:
+    def __init__(self, name, age):
+        self.name = name
+        self.age = age
+
+    def display_person_info(self):
+        print(f"Person: {self.name}, {self.age}")
+
+class Company:
+    def __init__(self, name, city):
+        self.company_name = name
+        self.location = city
+
+    def display_company_info(self):
+        print(f"Company: {self.company_name}, {self.location}")
+
+class Employee:
+    def __init__(self, name, age, company, city):
+        self.personal_data = Person(name, age)
+        self.work = Company(company, city)
+
+# ````````````````````````````````````````````````````````````````
+
+class Task:
+    def __init__(self, name, description, status=False):
+        self.name = name
+        self.description = description
+        self.status = status
+
+    def display(self):
+        print(f"{self.name} {'(Сделана)' if self.status else '(Не сделана)'}")
+
+class TaskList:
+    def __init__(self):
+        self.tasks = []
+
+    def add_task(self, task: Task):
+        self.tasks.append(task)
+
+    def remove_task(self, task: Task):
+        self.tasks.remove(task)
+
+class TaskManager:
+    def __init__(self, task_list:TaskList):
+        self.task_list = task_list
+
+    def mark_done(self, task:Task):
+        task.status = True
+    
+    def mark_undone(self, task:Task):
+        task.status = False
+    
+    def show_tasks(self):
+        for task in self.task_list.tasks:
+            task.display()
+
+# ````````````````````````````````````````````````````````````````
+class Triangle:
+    def __init__(self, a, b, c):
+        self.a = a
+        self.b = b
+        self.c = c
+    def is_exists(self):
+        return (self.a < (self.b + self.c)) and \
+                (self.b < (self.a + self.c)) and \
+                (self.c < (self.a + self.b))
+
+    def is_equilateral(self):
+        return self.a == self.b == self.c
+    
+    def is_isosceles(self):
+        return self.is_exists() and ((self.a == self.b) or (self.a == self.c) or (self.b == self.c))
+        
+
+# ````````````````````````````````````````````````````````````````
+
 class Config:
     pass
 
@@ -14,8 +91,13 @@ def create_instance(number: int):
 
 
 def main():
-    config = create_instance(3)
-    print(config.__dict__)
+    # config = create_instance(3)
+    # print(config.__dict__)
+
+    triangle = Triangle(5, 16, 5)
+    print(f"Is Triangle exist: {triangle.is_exists()}")
+    print(f"Is Equilateral: {triangle.is_equilateral()}")
+    print(f"Is Isosceles: {triangle.is_isosceles()}")
 
 
 if __name__ == '__main__':