Last active
May 2, 2019 18:13
-
-
Save jg75/93c7ce4f67b12265f970b1e011eef08f to your computer and use it in GitHub Desktop.
super's behavior and method resolution order in multiple inheritance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
MRO (Method Resolution Order) with multiple inheritance is resolved via | |
a linearization algorithm that flattens a tree. In some cases, super() | |
is not bound to a classes superclass, but instead to a sibling depending | |
on the object's MRO. | |
""" | |
class Base: | |
def __init__(self, field, **kwargs): | |
self.field = field | |
mro = " -> ".join([c.__name__ for c in self.__class__.__mro__]) | |
print(f"Base.__init__({kwargs})") | |
print(f"mro: {mro}") | |
def instance_method(self): | |
print(f"Base.instance_method called from: {self.__class__.__name__}") | |
def __contains__(self, string): | |
return string in self.field | |
def __len__(self): | |
return len(self.field) | |
class Class1(Base): | |
def __init__(self, field, **kwargs): | |
print(f"Class1.__init__({kwargs})") | |
self.field1 = kwargs.pop("field1", "default1") | |
super().__init__(field, **kwargs) | |
def instance_method(self): | |
print("Class1") | |
super().instance_method() | |
class Class2(Base): | |
def __init__(self, field, **kwargs): | |
print(f"Class2.__init__({kwargs})") | |
self.field2 = kwargs.pop("field2", "default2") | |
super().__init__(field, **kwargs) | |
def instance_method(self): | |
print("Class2") | |
super().instance_method() | |
class Class3(Class1, Class2): | |
def __init__(self, field, **kwargs): | |
print(f"Class3.__init__({kwargs})") | |
super().__init__(field, **kwargs) | |
def instance_method(self, derived_class=None): | |
print() | |
print("=" * 60) | |
print(f"super of {derived_class.__name__}") | |
if derived_class: | |
super(derived_class, self).instance_method() | |
else: | |
super().instance_method() | |
print("=" * 60) | |
if __name__ == "__main__": | |
class3 = Class3("data", field1="data1") | |
class3.instance_method(derived_class=Class3) | |
class3.instance_method(derived_class=Class2) | |
class3.instance_method(derived_class=Class1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment