Change python mro at runtime

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

    My solution would be to ask for forgiveness:

    class A(object):
        def __init__(self):
            print self.__class__
            print "__init__ A"
            self.hello()
    
        def hello(self):
            print "A hello"
    
    class B(A):
        def __init__(self):
            super(B, self).__init__()
            print "__init__ B"
            self.msg_str = "B"
            self.hello()
    
        def hello(self):
            try:
                print "%s hello" % self.msg_str
            except AttributeError:
                pass  # or whatever else you want
    
    a = A()
    b = B()
    

    or if you do not want to refactor methods called from init:

    class A(object):
        def __init__(self):
            print self.__class__
            print "__init__ A"
            self.hello()
    
        def hello(self):
            print "A hello"
    
    class B(A):
        def __init__(self):
            try:
                super(B, self).__init__()
            except AttributeError:
                pass  # or whatever else you want
            print "__init__ B"
            self.msg_str = "B"
            self.hello()
    
        def hello(self):
            print "%s hello" % self.msg_str
    
    a = A()
    b = B()
    

提交回复
热议问题