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!
相关推荐
用户83562907805112 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户83562907805112 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
karry_k12 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
karry_k12 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端
SamDeepThinking16 小时前
从源码到代码:MyBatis-Flex 与 MyBatis-Plus 的逐项对比
java·后端·程序员
她的男孩19 小时前
Spring Boot 接 Flowable 工作流:用 3 个注解搭一个请假审批流程
java·后端·架构
你好潘先生20 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师20 小时前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码20 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python