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!
相关推荐
红尘炼丹客3 分钟前
《DeepSeek-OCR: Contexts Optical Compression》速览
人工智能·python·自然语言处理·ocr
Dxxyyyy9 分钟前
零基础学JAVA--Day26(枚举类)
java·开发语言
☼←安于亥时→❦10 分钟前
Playwright 安装与使用
python·playwright
好望角雾眠15 分钟前
第四阶段C#通讯开发-6:Socket之UDP
开发语言·笔记·学习·udp·c#
黑屋里的马20 分钟前
java的设计模式之桥接模式(Bridge)
java·算法·桥接模式
升鲜宝供应链及收银系统源代码服务23 分钟前
升鲜宝生鲜配送供应链管理系统---PMS--商品品牌多语言存储与 Redis 缓存同步实现
java·开发语言·数据库·redis·缓存·开源·供应链系统
大佬,救命!!!26 分钟前
python实现象棋
开发语言·python·学习笔记·pygame·少儿编程·记录成长
棉猴26 分钟前
《pygame中Sprite类实现多帧动画》注-通过多张序列帧显示动画2-2
开发语言·python·游戏·游戏程序·pygame
练习时长一年34 分钟前
Spring AoP的切点匹配
java·开发语言