python在不改变类的基础上,从外面添加新的方法

python在不改变类的基础上,从外面添加新的方法

使用types.MethodType:

types.MethodType允许你将一个函数转换为一个方法,然后将其绑定到类上

python 复制代码
import types

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

def new_method(cls_instance):
    print(f"The value is {cls_instance.value}")

# 使用types.MethodType将函数转换为方法
MyClass.new_method = types.MethodType(new_method, MyClass)

# 现在MyClass有一个新方法new_method
obj = MyClass(10)
obj.new_method()  # 输出: The value is 10

直接通过类字典赋值:

直接给类的字典添加方法是一种更简单直接的方式。

python 复制代码
class MyClass:
    def __init__(self, value):
        self.value = value

def new_method(self):
    print(f"The value is {self.value}")

# 直接将函数new_method添加到MyClass的字典中
MyClass.new_method = new_method

# 现在MyClass有一个新方法new_method
obj = MyClass(10)
obj.new_method()  # 输出: The value is 10

使用类装饰器:

类装饰器是一种在定义后修改类的方式,可以在类定义后添加方法

python 复制代码
def add_method(cls):
    def new_method(self):
        print("Hello from the new method!")
    
    # 添加方法到类
    cls.new_method = new_method
    return cls

@add_method
class MyClass:
    pass

# 现在MyClass有一个新方法new_method
obj = MyClass()
obj.new_method()  # 输出: Hello from the new method!
相关推荐
旧故新长7 分钟前
Browserless 快速上手
java
java1234_小锋12 分钟前
Spring Bean有哪几种配置方式?
java·后端·spring
?abc!13 分钟前
缓存(5):常见 缓存数据淘汰算法/缓存清空策略
java·算法·缓存
DanB2426 分钟前
Java笔记4
java·开发语言·笔记
achene_ql30 分钟前
深入探索 RKNN 模型转换之旅
python·目标检测·rk3588·模型部署·rk3566
Dddle134 分钟前
C++:this指针
java·c语言·开发语言·c++
studyer_domi38 分钟前
Matlab 234-锂电池充放电仿真
开发语言·matlab
yuanpan1 小时前
.net/C#进程间通信技术方案总结
开发语言·c#·.net
吃面不喝汤661 小时前
破解 Qt QProcess 在 Release 模式下的“卡死”之谜
开发语言·qt
阿乾之铭1 小时前
Spring Boot 参数验证
java·数据库·mysql