在python中将基类添加到现有对象 [英] Adding base class to existing object in python

查看:108
本文介绍了在python中将基类添加到现有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个不同类型的对象(不同的函数名称,不同的签名),我将它们修改为具有从不同函数访问它们的通用方法。简而言之,有一个调度程序可以获取我想要修补的对象,并根据它调用不同修补程序的对象类型。修补程序将向对象添加方法:

I have several objects of different kinds (different function names, different signatures) and I monkey patch them to have a common way to access them from different functions. Briefly, there is a dispatcher that takes the objects that I want to patch and depending on the object type it calls different patcher. A patcher will add methods to the object:

def patcher_of_some_type(object):

    def target(self, value):
        # do something and call self methods

    object.target = types.MethodType(target, object)

    # many more of these

随着程序变得越来越复杂,使对象(或对象类)周围的包装看起来更好理念。一些修补程序共享公共代码或相互关联。但我不控制对象创建,也不控制类创建。我只得到了这些物品。即使我能做到这一点,我只想包装(或修补)某些对象,而不是全部。

As the program grows more complicated making a wrapper around the object (or the object class) seems to be better idea. Some patchers share common code or are interrelated. But I do not control the object creation, nor the class creation. I only get the objects. And even if I could do that, I just want to wrap (or patch) certain objects, not all.

一个解决方案可能是为现有对象添加基类,但我不确定这是多么可维护和安全。还有其他解决方案吗?

One solution might be add a base class to an existing object, but I am not sure how maintainable and safe this is. Is there another solution?

推荐答案

动态修改对象的类型是相当安全的,只要额外的基类兼容(和如果不是,你会得到一个例外)。添加基类的最简单方法是使用3参数类型构造函数:

Dynamically modifying an object's type is reasonably safe, as long as the extra base class is compatible (and you'll get an exception if it isn't). The simplest way to add a base class is with the 3-argument type constructor:

cls = object.__class__
object.__class__ = cls.__class__(cls.__name__ + "WithExtraBase", (cls, ExtraBase), {})

这篇关于在python中将基类添加到现有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆