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 分钟前
【C++】priority_queue和deque的使用与实现
开发语言·c++·学习
货拉拉技术20 分钟前
网关 MCP 转换技术:从实现到平台落地
java·架构·mcp
艾菜籽20 分钟前
SpringMVC练习:加法计算器与登录
java·spring boot·spring·mvc
啊森要自信21 分钟前
【GUI自动化测试】Python 自动化测试框架 pytest 全面指南:基础语法、核心特性(参数化 / Fixture)及项目实操
开发语言·python·ui·单元测试·pytest
赵谨言32 分钟前
基于python智能家居环境质量分析系统的设计与实现
开发语言·经验分享·python·智能家居
元亓亓亓1 小时前
考研408--组成原理--day1
开发语言·javascript·考研·计组
Yurko131 小时前
【C语言】环境安装(图文)与介绍
c语言·开发语言·学习
浮游本尊1 小时前
Java学习第25天 - Spring Cloud Alibaba微服务生态
java
仲星(._.)1 小时前
C语言:字符函数和字符串函数
c语言·开发语言
kyle~1 小时前
C++---向上取整
开发语言·c++