# Python Advanced Course
[toc]
## Lec 1 Class (4/13)
- Basic class
```python
class Car():
"""This is a class of Car"""
def __init__(self, wheel, color) -> None:
self.wheel = wheel
self.color = color
def print(self):
"""Print the info of car"""
print(f'This is a {self.color} car with {self.wheel} wheels')
```
- Inheritance
```python
class Company():
def __init__(self, name) -> None:
self.name = name
def print(self) -> None:
print(f'{self.name} Inc. ')
class ASUS(Company):
def __init__(self, capital) -> None:
super().__init__('ASUS')
self.capitol = capital
def print_Asus(self) -> None:
print(f'{self.name} Inc. has {self.capital} money')
```
- Polymorphism
```python
class Company():
def __init__(self, name) -> None:
self.name = name
def print(self) -> None:
print(f'{self.name} Inc. ')
class ASUS(Company):
def __init__(self, capital) -> None:
super().__init__('ASUS')
self.capitol = capital
def print(self) -> None:
print(f'{self.name} Inc. has {self.capital} money')
```
```python
class Point():
def __init__(self, x, y) -> None:
self.x = x
self.y = y
def __add__(self, other) -> 'Point':
new_x = self.x + other.x
new_y = self.y + other.y
return Point(new_x, new_y)
def __str__(self) -> str:
return f'({self.x}, {self.y})'
a1 = Point(1, 8)
a2 = Point(10, 3)
a3 = a1 + a2
print(a3)
```
- Encapsulation
```python
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if self.__balance >= amount:
self.__balance -= amount
else:
print("Insufficient balance.")
def get_balance(self):
return self.__balance
my_account = BankAccount(100.0)
my_account.deposit(50.0)
print(my_account.get_balance()) # 150.0
print(my_account.__balance) # Error
```
- Access Modifiers
```python
class MyPrivateClass:
def __init__(self):
self.__my_private_variable = 10
def __my_private_method(self):
print("This is a private method")
def my_public_method(self):
self.__my_private_method()
class MyClass:
def __init__(self):
self._my_protected_variable = 10
def _my_protected_method(self):
print("This is a protected method")
class MySubclass(MyClass):
def my_public_method(self):
self._my_protected_method()
```
- Decorators
```python
def print_func_name(func):
def wrap(name):
print(f"Now use function '{func.__name__}'")
func(name)
return wrap
def print_Hello(name):
print(f'Hello, {name}')
print_func_name(print_Hello)('Allen')
```
```python
def print_func_name(func):
def wrap(name):
print(f"Now use function '{func.__name__}'")
func(name)
return wrap
@print_func_name
def print_Hello(name):
print(f'Hello, {name}')
print_Hello('Allen')
```
```python
import time
def print_func_name(time):
def decorator(func):
def wrap(name):
print(f"Now use function '{func.__name__}'")
print(f"Now Unix time is {int(time)}.")
func(name)
return wrap
return decorator
@print_func_name(time=time.time())
def print_Hello(name):
print(f'Hello, {name}')
print_Hello('Wilson')
```