Change python mro at runtime

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

    I'd like to point out a solution which is very specific to the example you present in your question, and therefor unlikely to help. (But in case it does help at all...)

    You can bypass hello's polymorphism by defining it as a class member, instead of a method.

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

    (A remains unchanged).

    This solution will break if:

    • you subclass B and need to override hello in the subclass
    • msg_str is modified after __init__ runs
    • probably several other cases...

提交回复
热议问题