关于门户网站建设的整改报告,微信网站模板,如何设计一个公司的网页,加强网站内容保密建设在 Python 中#xff0c;类方法 (classmethod) 和静态方法 (staticmethod) 是类作用域下的两种特殊方法。它们使用装饰器定义#xff0c;并且与实例方法 (def func(self)) 的行为有所不同。1. 三种方法的对比概览方法类型是否访问实例 (self)是否访问类 (cls)典型用途实例方法…在 Python 中类方法 (classmethod) 和静态方法 (staticmethod) 是类作用域下的两种特殊方法。它们使用装饰器定义并且与实例方法 (def func(self)) 的行为有所不同。1. 三种方法的对比概览方法类型是否访问实例 (self)是否访问类 (cls)典型用途实例方法✅ 是❌ 否访问对象属性类方法 classmethod❌ 否✅ 是创建类的替代构造器访问类变量等静态方法 staticmethod❌ 否❌ 否工具函数与类逻辑相关但不依赖类或实例
2. 实例方法默认方法
class MyClass:def instance_method(self):print(fThis is an instance method. self {self})obj MyClass()
obj.instance_method() # 输出 self 为该实例3. 类方法 classmethod
class MyClass:class_var Hello, Class!classmethoddef class_method(cls):print(fThis is a class method. cls {cls})print(fAccess class_var {cls.class_var})MyClass.class_method() # 通过类调用
obj MyClass()
obj.class_method() # 通过实例也可以调用特点第一个参数是 cls代表类本身常用于
构造不同初始化方式修改/访问类变量工厂模式 (from_* 等)示例类方法作为工厂方法
class Book:def __init__(self, title, author):self.title titleself.author authorclassmethoddef from_string(cls, book_str):title, author book_str.split(,)return cls(title.strip(), author.strip())book Book.from_string(1984, George Orwell)
print(book.title) # ➜ 19844. 静态方法 staticmethod
class MyMath:staticmethoddef add(x, y):return x yprint(MyMath.add(3, 5)) # ➜ 8特点不接收 self 或 cls 参数和普通函数类似但归属在类中逻辑上与类相关常用于
与类操作相关的工具方法不需要访问类或实例内部状态示例静态方法作为工具函数
class Temperature:def __init__(self, celsius):self.celsius celsiusstaticmethoddef to_fahrenheit(c):return c * 9 / 5 32def show(self):print(f{self.celsius}°C {self.to_fahrenheit(self.celsius)}°F)temp Temperature(25)
temp.show() # ➜ 25°C 77.0°F总结何时用哪种方法场景推荐方法需要访问或修改实例属性实例方法需要访问或修改类变量、类构造类方法 classmethod工具函数与类相关但不访问类或实例成员静态方法 staticmethod
classmethod 和 staticmethod 应用场景实战
利用 Python 中的 classmethod 和 staticmethod 可以优雅地实现设计模式如单例模式和工厂模式。下面我将分别讲解这两种模式的原理、适用场景并结合代码示例说明如何使用类方法或静态方法实现。1、工厂模式Factory Pattern
定义工厂模式是一种创建对象的设计模式它允许类在创建对象时不暴露实例化逻辑而是通过类方法返回不同的类实例。
使用类方法实现工厂模式
class Animal:def __init__(self, name):self.name nameclassmethoddef create_dog(cls):return cls(Dog)classmethoddef create_cat(cls):return cls(Cat)# 使用工厂方法创建对象
dog Animal.create_dog()
cat Animal.create_cat()print(dog.name) # ➜ Dog
print(cat.name) # ➜ Cat应用场景
多种初始化方式如从字符串、文件、数据库等根据条件返回不同子类对象
更复杂示例带注册机制的工厂
class ShapeFactory:_creators {}classmethoddef register(cls, name, creator):cls._creators[name] creatorclassmethoddef create(cls, name, *args, **kwargs):if name not in cls._creators:raise ValueError(fUnknown shape: {name})return cls._creators[name](*args, **kwargs)# 各种 Shape 类
class Circle:def __init__(self, radius):self.radius radiusclass Square:def __init__(self, length):self.length length# 注册
ShapeFactory.register(circle, Circle)
ShapeFactory.register(square, Square)# 创建对象
c ShapeFactory.create(circle, 5)
s ShapeFactory.create(square, 3)
print(c.radius) # ➜ 5
print(s.length) # ➜ 32、单例模式Singleton Pattern
定义单例模式保证类在程序中只有一个实例。
使用类方法实现单例
class Singleton:_instance Noneclassmethoddef get_instance(cls):if cls._instance is None:cls._instance cls()return cls._instance# 测试
a Singleton.get_instance()
b Singleton.get_instance()
print(a is b) # ➜ True也可以结合 __new__ 实现单例
class Singleton:_instance Nonedef __new__(cls, *args, **kwargs):if not cls._instance:cls._instance super().__new__(cls)return cls._instance# 所有实例是同一个
a Singleton()
b Singleton()
print(a is b) # ➜ True3、静态方法在设计模式中的作用
工具类模式Utility Pattern
静态方法常用于实现工具类即所有方法都与对象状态无关仅执行逻辑计算。
class MathUtils:staticmethoddef add(x, y):return x ystaticmethoddef multiply(x, y):return x * yprint(MathUtils.add(3, 4)) # ➜ 7
print(MathUtils.multiply(3, 4)) # ➜ 124、小结设计模式推荐使用原因工厂模式classmethod需要访问类构造器、支持多种创建方式单例模式classmethod / __new__控制实例生成的唯一性工具类staticmethod无需访问类/实例仅提供辅助功能