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):
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.
Call self.msg_str = "B"
before super(B, self).__init__()
.