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):
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):
print "%s hello" % self.msg_str
a = A()
b = B()
As to be expected, this fails as the __init__ method of A (when called from B) calls B's hello which attempts to access an attribute before it exists.
The issue is that I'm constrained in the changes I can make:
- B must subclass A
- A cannot be changed
- Both A and B require a hello method
- B cannot initialise other attributes before calling the super
__init__
I did solve this conceptually, by changing the MRO at runtime. In brief, during B's __init__, but before calling super __init__, the MRO would be changed so that A would be searched for methods first, thereby calling A's hello instead of B's (and therefore failing).
The issue is that MRO is read only (at class runtime).
Is there another way to implement this ? Or possibly a different solution altogether (that still respects the aforementioned constraints) ?