Python 类中方法类型详解

三种方法类型对比

方法类型 装饰器 第一个参数 调用者 自动传参
实例方法 self (实例本身) 实例对象 ✅ 自动传入实例
类方法 @classmethod cls (类本身) 类或实例 ✅ 自动传入类
静态方法 @staticmethod 类或实例 ❌ 无自动传参

详细示例

实例方法 (Instance Method)

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    # 实例方法 - 绑定到对象
    def introduce(self):
        # 自动传入当前实例作为第一个参数 self
        return f"我叫{self.name},今年{self.age}岁"

# 使用
stu = Student("张三", 20)
print(stu.introduce())  # 自动将 stu 作为 self 传入
# 输出: 我叫张三,今年20岁

# 实际上等价于:
print(Student.introduce(stu))

类方法 (Class Method)

class Student:
    school = "清华大学"
    count = 0
    
    def __init__(self, name):
        self.name = name
        Student.count += 1
    
    @classmethod  # 绑定到类的方法
    def get_school_info(cls):
        # 自动传入类作为第一个参数 cls
        return f"学校: {cls.school}, 学生总数: {cls.count}"
    
    @classmethod
    def create_student(cls, name):
        # 类方法可以作为替代构造器
        return cls(name)  # 相当于 Student(name)

# 使用
print(Student.get_school_info())  # 自动将 Student 作为 cls 传入
# 输出: 学校: 清华大学, 学生总数: 0

stu1 = Student.create_student("李四")  # 使用类方法创建实例
print(Student.get_school_info())
# 输出: 学校: 清华大学, 学生总数: 1

# 实例也可以调用类方法,但传入的仍然是类
print(stu1.get_school_info())
# 输出: 学校: 清华大学, 学生总数: 1

静态方法 (Static Method)

class MathUtils:
    @staticmethod  # 非绑定方法
    def add(x, y):
        # 没有自动传入的参数
        return x + y
    
    @staticmethod
    def is_adult(age):
        return age >= 18

# 使用
# 通过类调用
result1 = MathUtils.add(5, 3)
print(result1)  # 8

# 通过实例调用
math_utils = MathUtils()
result2 = math_utils.add(10, 20)
print(result2)  # 30

# 静态方法没有自动传参,参数需要显式传递
print(MathUtils.is_adult(20))  # True
print(math_utils.is_adult(15)) # False

综合示例

class Calculator:
    # 类属性
    operation_count = 0
    
    def __init__(self, brand):
        self.brand = brand
    
    # 实例方法 - 操作实例数据
    def set_brand(self, new_brand):
        self.brand = new_brand
        return f"品牌已设置为: {self.brand}"
    
    # 类方法 - 操作类数据
    @classmethod
    def increment_count(cls):
        cls.operation_count += 1
        return f"操作次数: {cls.operation_count}"
    
    # 静态方法 - 独立功能,不依赖类或实例
    @staticmethod
    def calculate_average(numbers):
        if not numbers:
            return 0
        return sum(numbers) / len(numbers)
    
    # 另一个实例方法,演示混合使用
    def perform_calculation(self, numbers):
        result = self.calculate_average(numbers)  # 调用静态方法
        count = self.increment_count()  # 调用类方法
        return f"{self.brand}计算器: 平均值={result}, {count}"

# 测试使用
calc = Calculator("卡西欧")

# 实例方法调用
print(calc.set_brand("卡西欧高级版"))
# 输出: 品牌已设置为: 卡西欧高级版

# 静态方法调用
numbers = [1, 2, 3, 4, 5]
avg = Calculator.calculate_average(numbers)
print(f"平均值: {avg}")  # 输出: 平均值: 3.0

# 类方法调用
print(Calculator.increment_count())  # 输出: 操作次数: 1

# 混合调用
print(calc.perform_calculation([10, 20, 30]))
# 输出: 卡西欧高级版计算器: 平均值=20.0, 操作次数: 2

使用场景总结

实例方法

  • 用途: 操作和访问实例特有的数据
  • 特征: 需要访问 self 的属性或方法
  • 示例: obj.method()

类方法

  • 用途:
    • 操作类属性(类级别的状态)
    • 创建替代构造器
    • 在继承中多态地创建对象
  • 特征: 需要访问 cls 或操作类级别的数据
  • 示例: Class.method()obj.method()

静态方法

  • 用途:
    • 工具函数,与类相关但不依赖类或实例状态
    • 组织代码,逻辑上属于类但功能独立
  • 特征: 不需要访问类或实例的任何属性
  • 示例: Class.method()obj.method()

继承中的行为

class Animal:
    @classmethod
    def create(cls):
        return cls()  # 多态:返回调用者的实例
    
    @staticmethod
    def make_sound():
        return "Some sound"

class Dog(Animal):
    @staticmethod
    def make_sound():
        return "Woof!"

# 测试
animal = Animal.create()
dog = Dog.create()

print(type(animal))  # <class '__main__.Animal'>
print(type(dog))     # <class '__main__.Dog'>

print(Animal.make_sound())  # Some sound
print(Dog.make_sound())     # Woof!

关键记忆点

  1. 实例方法: self → 操作对象数据
  2. 类方法: @classmethod + cls → 操作类数据
  3. 静态方法: @staticmethod → 独立工具函数

记住:绑定 = 自动传参,非绑定 = 手动传参

posted @ 2025-10-10 08:32  Ciyang_Wu  阅读(8)  评论(0)    收藏  举报