Change python mro at runtime

后端 未结 8 2406
我寻月下人不归
我寻月下人不归 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:56

    For your particular example, one solution is to give B a class attribute to hold a default message:

    class B(A):
    
        msg_str = "default msg"
    
        def __init__(self):
            super(B, self).__init__()
            print "__init__ B"
            self.msg_str = "B"
            self.hello()
    
        def hello(self):
            print "%s hello" % self.msg_str
    

    Usually this causes confusion, but in this case it might be helpful. If B.hello is called before the instance's msg_str is set, it will read the class one. Once the instance msg_str is set, it shadows the class one so that future accesses of self.msg_str will see the instance-specific one.

    I don't quite understand why you can't set attributes before calling the superclass __init__. Depending on exactly what the underlying situation is, there may be other solutions.

    0 讨论(0)
  • 2020-12-15 09:59

    Call self.msg_str = "B" before super(B, self).__init__().

    0 讨论(0)
提交回复
热议问题