类方法

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
Python 面向对象编程入门

类方法

  • 可以定义类方法
  • 作用域应窄,因为无法使用对象级数据
class MyClass:
    # 使用装饰器声明类方法
    @classmethod

# cls 参数指向类本身 def my_awesome_method(cls, args...): # 在此编写逻辑 # 不能使用任何实例属性
# 调用类,而非对象 MyClass.my_awesome_method(args...)
  • self 一样,cls 只是约定,任意名称都可
Python 面向对象编程入门

备用构造器

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__(...)
Python 面向对象编程入门

备用构造器

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.txt

包含姓名 John Smith 和薪资 40000 的文本文件

# 不直接调用 Employee() 创建员工
emp = Employee.from_file("employee_data.txt")
print(emp.name)
John Smith
Python 面向对象编程入门

何时使用类方法

  • 备用构造器

  • 不需要实例级属性的方法

  • 限制类为单一实例(对象)

    • 数据库连接
    • 配置设置
Python 面向对象编程入门

Passons à la pratique !

Python 面向对象编程入门

Preparing Video For Download...