Python 物件導向程式設計入門
George Boorman
Curriculum Manager, DataCamp
class Employee: def __init__(self, name, salary): self.name = name self.salary = salary def give_raise(self, amount): self.salary += amount# Unique attribute values emp_one = Employee("John", 40000)emp_one.give_raise(5000) print(emp_one.salary)
45000
# Unique attribute values emp_two = Employee("Jane", 60000)emp_two.give_raise(5000) print(emp_two.salary)
65000
class MyClass: # 用裝飾器宣告類別方法 @classmethod# 參數 cls 指向類別本身 def my_awesome_method(cls, args...): # 在這裡處理 # 不能使用實例屬性# 呼叫類別,不是物件 MyClass.my_awesome_method(args...)
self 一樣,cls 是慣例,任意名稱都可class Employee: def __init__(self, name, salary): self.name = name self.salary = salary@classmethod def from_file(cls, filename): with open(filename, "r") as f: # 讀取第一行 name = f.readline().strip() # 第二行讀為整數 salary = int(f.readline().strip())return cls(name, salary)
__init__() 只能有一個
return 傳回物件cls(...) 會呼叫 __init__(...)class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
@classmethod
def from_file(cls, filename):
with open(filename, "r") as f:
name = f.readline().strip()
salary = int(f.readline().strip())
return cls(name, salary)

# 不用直接呼叫 Employee() 建立員工
emp = Employee.from_file("employee_data.txt")
print(emp.name)
John Smith
替代建構子
不需實例層級屬性的方式
將類別限制為單一實例(物件)
Python 物件導向程式設計入門