Python 物件導向程式設計入門
George Boorman
Curriculum Manager, 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 Employee: # Define a class attribute # No self. syntax MIN_SALARY = 30000def __init__(self, name, salary): self.name = name # Use class name # to access class attribute if salary >= Employee.MIN_SALARY: self.salary = salaryelse: self.salary = Employee.MIN_SALARY
MIN_SALARY 由所有物件共享selfClassName.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("John", 40000)
print(emp1.MIN_SALARY)
30000
emp2 = Employee("Jane", 60000)
print(emp2.MIN_SALARY)
30000
emp1 = Employee("John", 40000) emp2 = Employee("Jane", 60000)# Update MIN_SALARY of emp1 emp1.MIN_SALARY = 50000# Print MIN_SALARY for both employees print(emp1.MIN_SALARY) print(emp2.MIN_SALARY)
50000
30000
MIN_SALARY 在類別定義中建立
MIN_SALARY,不會影響類別定義裡的值
Database 類別的 host、portPython 物件導向程式設計入門