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!
相关推荐
wjs20242 小时前
状态模式(State Pattern)
开发语言
我命由我123452 小时前
Kotlin 数据容器 - List(List 概述、创建 List、List 核心特性、List 元素访问、List 遍历)
java·开发语言·jvm·windows·java-ee·kotlin·list
liulilittle2 小时前
C++ TAP(基于任务的异步编程模式)
服务器·开发语言·网络·c++·分布式·任务·tap
im_AMBER3 小时前
学习日志19 python
python·学习
励志要当大牛的小白菜4 小时前
ART配对软件使用
开发语言·c++·qt·算法
武子康4 小时前
Java-80 深入浅出 RPC Dubbo 动态服务降级:从雪崩防护到配置中心秒级生效
java·分布式·后端·spring·微服务·rpc·dubbo
mortimer6 小时前
安装NVIDIA Parakeet时,我遇到的两个Pip“小插曲”
python·github
@昵称不存在6 小时前
Flask input 和datalist结合
后端·python·flask
爱装代码的小瓶子6 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
赵英英俊7 小时前
Python day25
python