Adding base class to existing object in python

后端 未结 3 1725
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-11 22:28

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 functio

3条回答
  •  自闭症患者
    2021-01-11 23:24

    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), {})
    

提交回复
热议问题