文章目录
前言
以下是Python中五种类方法(类方法、实例方法、自由方法、静态方法、保留方法)的详细解释及代码示例,按使用场景和特性分类说明
一、实例方法 (Instance Method)
定义:默认方法类型,绑定到类实例,可访问实例属性
特点:
1.> 第一个参数必须是self(指向实例)
2.> 只能通过实例调用
用途:
操作实例及数据
class Dog:
def __init__(self, name):
self.name = name # 实例属性
# 实例方法
def bark(self):
print(f"{self.name} says Woof!")
d = Dog("Buddy")
d.bark() # 输出:Buddy says Woof!
二、类方法 (Class Method)
定义:绑定到类本身,可修改类状态
特点:
1.> 使用@classmethod装饰器
2.> 第一个参数为cls(指向类)
3.> 可通过类或实例调用
用途:
工厂模式、操作类属性
class Cat:
total_cats = 0 # 类属性
@classmethod
def count_cats(cls):
print(f"Total cats: {cls.total_cats}")
def __init__(self):
Cat.total_cats += 1
Cat.count_cats() # 输出:Total cats: 0
c1 = Cat()
c1.count_cats() # 输出:Total cats: 1
三、静态方法 (Static Method)
定义:与类和实例无绑定关系,相当于普通函数
特点:
1.> 使用@staticmethod装饰器
2.> 无self或cls参数
3.> 可通过类或实例调用
用途:
工具函数、与类逻辑相关但不依赖类状态的操作
class Calculator:
@staticmethod
def add(a, b):
return a + b
print(Calculator.add(3, 5)) # 输出:8
calc = Calculator()
print(calc.add(10, 20)) # 输出:30
四、自由方法 (自由函数)
定义:定义在类中的普通函数,无装饰器
特点:
1.> 无自动参数传递(无self/cls)
2.> 必须通过类名显式调用
用途:
罕见,通常应使用静态方法替代
class Logger:
def write_log(msg): # 自由方法
print(f"[LOG] {msg}")
Logger.write_log("Error occurred") # 正确调用
# Logger().write_log("test") # 报错:缺少参数
五、保留方法 (Magic/Dunder Methods)
定义:以双下划线__包围的特殊方法
特点:
1.> Python解释器自动调用
2.> 实现运算符重载、对象生命周期管理等
用途:
自定义类行为
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
# 保留方法:实现+运算符
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
# 保留方法:字符串表示
def __str__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(4, 5)
print(v1 + v2) # 输出:Vector(6, 8)
六、对比总结表
总结
Python中五种类方法(类方法、实例方法、自由方法、静态方法、保留方法)的简单举例和应用,对初学者希望有帮助。
感谢大家的点赞收藏转发和关注,谢谢你。