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: # Read the first line name = f.readline().strip() # Read the second line as integer 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 面向对象编程入门