Python 物件導向程式設計
Alex Yarosh
Content Quality Analyst @ DataCamp
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
emp1 = Employee("Teo Mille", 50000)
emp2 = Employee("Marta Popov", 65000)
name、salary 是實例屬性self 綁定到某個實例class 本體中定義類別屬性class MyClass:
# Define a class attribute
CLASS_ATTR_NAME = attr_value
class Employee: # Define a class attribute MIN_SALARY = 30000 #<--- no self.def __init__(self, name, salary): self.name = name # Use class name to access class attribute if salary >= Employee.MIN_SALARY: self.salary = salary else: self.salary = Employee.MIN_SALARY
MIN_SALARY 由所有實例共享self 來_定義_類別屬性ClassName.ATTR_NAME 來_存取_類別屬性的值class Employee: # Define a class attribute MIN_SALARY = 30000def __init__(self, name, salary): self.name = name # Use class name to access class attribute if salary >= Employee.MIN_SALARY: self.salary = salary else: self.salary = Employee.MIN_SALARY
emp1 = Employee("TBD", 40000)
print(emp1.MIN_SALARY)
30000
emp2 = Employee("TBD", 60000)
print(emp2.MIN_SALARY)
30000
Circle 類別的 piclass MyClass: @classmethod # <---use decorator to declare a class methoddef my_awesome_method(cls, args...): # <---cls argument refers to the class # Do stuff here # Can't use any instance attributes :(
MyClass.my_awesome_method(args...)
class Employee:
MIN_SALARY = 30000
def __init__(self, name, salary=30000):
self.name = name
if salary >= Employee.MIN_SALARY:
self.salary = salary
else:
self.salary = Employee.MIN_SALARY
__init__()
@classmethod
def from_file(cls, filename):
with open(filename, "r") as f:
name = f.readline()
return cls(name)
return 傳回物件cls(...) 會呼叫 __init__(...)class Employee:
MIN_SALARY = 30000
def __init__(self, name, salary=30000):
self.name = name
if salary >= Employee.MIN_SALARY:
self.salary = salary
else:
self.salary = Employee.MIN_SALARY
@classmethod
def from_file(cls, filename):
with open(filename, "r") as f:
name = f.readline()
return cls(name)

# 不用直接呼叫 Employee() 也能建立員工
emp = Employee.from_file("employee_data.txt")
type(emp)
__main__.Employee
Python 物件導向程式設計