Last active
September 27, 2017 18:28
-
-
Save xuhang57/f36da3badb373b3be20ce0d5c813cbf3 to your computer and use it in GitHub Desktop.
Super() in python
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
| # https://stackoverflow.com/a/33469090/8379419 | |
| # Dependency Injection | |
| # Other people can use your code and inject parents into the method resolution: | |
| class SomeBaseClass(object): | |
| def __init__(self): | |
| print('SomeBaseClass.__init__(self) called') | |
| class UnsuperChild(SomeBaseClass): | |
| def __init__(self): | |
| print('UnsuperChild.__init__(self) called') | |
| SomeBaseClass.__init__(self) | |
| class SuperChild(SomeBaseClass): | |
| def __init__(self): | |
| print('SuperChild.__init__(self) called') | |
| super(SuperChild, self).__init__() | |
| # Say you add another class to your object, and want to inject a class between Foo and Bar | |
| # (for testing or some other reason): | |
| class InjectMe(SomeBaseClass): | |
| def __init__(self): | |
| print('InjectMe.__init__(self) called') | |
| super(InjectMe, self).__init__() | |
| class UnsuperInjector(UnsuperChild, InjectMe): pass | |
| class SuperInjector(SuperChild, InjectMe): pass | |
| # Using the un-super child fails to inject the dependency because the child you're using has hard-coded | |
| # the method to be called after its own: | |
| >>> o = UnsuperInjector() | |
| UnsuperChild.__init__(self) called | |
| SomeBaseClass.__init__(self) called | |
| # However, the class with the child that uses super can correctly inject the dependency: | |
| >>> o2 = SuperInjector() | |
| SuperChild.__init__(self) called | |
| InjectMe.__init__(self) called | |
| SomeBaseClass.__init__(self) called |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment