Python 类装饰器详解

类装饰器是作用于类的装饰器,它可以修改或增强类的行为。

1. 基本概念和语法

什么是类装饰器

类装饰器是一个接收类作为参数并返回修改后类的可调用对象。

基本语法

python

@decorator
class MyClass:
    pass

# 等价于
MyClass = decorator(MyClass)

2. 函数形式的类装饰器

最简单的类装饰器

python

def add_methods(cls):
    """给类添加新方法的装饰器"""
    def new_method(self):
        return f"这是添加的方法,类名: {self.__class__.__name__}"
    
    cls.new_method = new_method
    cls.description = "这是装饰器添加的属性"
    return cls

@add_methods
class MyClass:
    def __init__(self, value):
        self.value = value

# 使用
obj = MyClass(42)
print(obj.new_method())  # 这是添加的方法,类名: MyClass
print(obj.description)   # 这是装饰器添加的属性

带参数的类装饰器

def add_attributes(**kwargs): #** 操作符直接打包参数包为字典
    """给类添加属性的装饰器工厂"""
    def decorator(cls):
        for key, value in kwargs.items():
            setattr(cls, key, value) # 内置方法,设置参数
        return cls
    return decorator

@add_attributes(version="1.0", author="John", created="2023")
class Calculator:
    def add(self, a, b):
        return a + b

# 使用
calc = Calculator()
print(calc.add(2, 3))    # 5
print(Calculator.version)  # 1.0
print(Calculator.author)   # John

3. 类形式的类装饰器

实现 __call__ 方法的类装饰器

class Singleton:
    """单例模式类装饰器"""
    def __init__(self, cls):
        self.cls = cls
        self.instance = None
    
    def __call__(self, *args, **kwargs): #让类可以像函数一样的调用
        if self.instance is None:
            self.instance = self.cls(*args, **kwargs)
        return self.instance

@Singleton
class DatabaseConnection:
    def __init__(self, connection_string):
        self.connection_string = connection_string
        print(f"创建数据库连接: {connection_string}")
    
    def query(self, sql):
        return f"执行: {sql}"

# 测试单例
db1 = DatabaseConnection("mysql://localhost:3306/mydb")
db2 = DatabaseConnection("mysql://localhost:3306/otherdb")

print(db1 is db2)  # True - 同一个实例
print(db1.connection_string)  # mysql://localhost:3306/mydb
# 注意:第二次创建时使用的参数被忽略了

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇