TelenkovDmitry 8 月之前
父節點
當前提交
1469bb9b09
共有 2 個文件被更改,包括 315 次插入0 次删除
  1. 158 0
      courses/python_oop/private.py
  2. 157 0
      courses/python_oop/property_method.py

+ 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()

+ 157 - 0
courses/python_oop/property_method.py

@@ -0,0 +1,157 @@
+
+# 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 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
+
+    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()