Change python mro at runtime

后端 未结 8 2416
我寻月下人不归
我寻月下人不归 2020-12-15 09:02

I\'ve found myself in an unusual situation where I need to change the MRO of a class at runtime.

The code:

class A(object):
    def __init__(self):
          


        
8条回答
  •  隐瞒了意图╮
    2020-12-15 09:46

    I've found a way to change object's class or rewrite it's mro.

    The easiest way is to build a new class with type function:

    def upgrade_class(obj, old_class, new_class):
        if obj.__class__ is old_class:
            obj.__class__ = new_class
        else:
            mro = obj.__class__.mro()
    
            def replace(cls):
                if cls is old_class:
                    return new_class
                else:
                    return cls
    
            bases = tuple(map(replace, mro[1:]))
            old_base_class = obj.__class__
            new_class = type(old_base_class.__name__, bases, dict(old_base_class.__dict__))
            obj.__class__ = new_class
    

提交回复
热议问题