先看最基本的 class。Employee 定義了員工的 attributes 和 methods,然後用它建立兩個 object(emp1、emp2),再讀它們的資料。
class Employee:
# constructor
def __init__(self, name, role, salary, city):
self.name = name
self.role = role
self.salary = salary
self.city = city
def getInfo(self):
print(f'name:{self.name}, role:{self.role}, salary:{self.salary}, city:{self.city}')
emp1 = Employee('Peter', 'Developer', 3000, 'HK')
emp2 = Employee('Mary', 'Manager', 5000, 'HK')
print(emp1.name)
emp1.getInfo()output:
Peter name:Peter, role:Developer, salary:3000, city:HK
- __init__ 是初始化方法(constructor),建立 object 時自動 call,用來設定 attributes。
- class 是 object 的藍圖(definition)。上面 Employee 就是藍圖,emp1、emp2 是它生出來的 object(instance)。
- class 的重要元素:attributes(instance 每個 object 獨立、class 級共享)+ methods(方法)。
- 變數分兩種:class variable(整個 class 共享)vs instance variable(每個 object 自己一份)。
- 方法分兩種:class method(用 cls,不用建立 instance)vs instance method(用 self)。
- 調用方向:instance 可以 call class 的東西,但 class 不可以直接 call instance 的東西。
