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!
相关推荐
2301_790300963 小时前
用Python读取和处理NASA公开API数据
jvm·数据库·python
m0_686041613 小时前
C++中的适配器模式变体
开发语言·c++·算法
清风~徐~来3 小时前
【视频点播系统】WebSocketpp 介绍及使用
开发语言
葱明撅腚3 小时前
利用Python挖掘城市数据
python·算法·gis·聚类
Serendipity_Carl3 小时前
1637加盟网数据实战(数分可视化)
爬虫·python·pycharm·数据可视化·数据清洗
爱吃大芒果3 小时前
Flutter for OpenHarmony 实战:mango_shop 路由系统的配置与页面跳转逻辑
开发语言·javascript·flutter
流㶡3 小时前
网络爬虫之requests.get() 之爬取网页内容
python·数据爬虫
学***54233 小时前
如何轻松避免网络负载过大
开发语言·网络·php
RANCE_atttackkk3 小时前
Springboot+langchain4j的RAG检索增强生成
java·开发语言·spring boot·后端·spring·ai·ai编程
梵刹古音3 小时前
【C语言】 格式控制符与输入输出函数
c语言·开发语言·嵌入式