Created
June 9, 2015 23:28
-
-
Save kirsle/c3417cf1a2bf73b26202 to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/env python | |
class WorkerBase(object): | |
def __init__(self, *args, **kwargs): | |
print "WorkerBase init" | |
pass | |
class DBWorker(WorkerBase): | |
def __init__(self, *args, **kwargs): | |
print "DBWorker init" | |
print "DBworker config:", kwargs["config"] | |
super(DBWorker, self).__init__(*args, **kwargs) | |
class LoggingWorker(WorkerBase): | |
def __init__(self, *args, **kwargs): | |
print "LoggingWorker init" | |
print "LoggingWorker config:", kwargs["config"] | |
super(LoggingWorker, self).__init__(*args, **kwargs) | |
class MyWorker(DBWorker, LoggingWorker): | |
def __init__(self, *args, **kwargs): | |
print "My worker init" | |
super(MyWorker, self).__init__(*args, **kwargs) | |
if __name__ == "__main__": | |
w = MyWorker(config="develop", hello="world") | |
""" | |
Demonstration for multiple inheritance. | |
Key notes: | |
* Your base classes (DBWorker, LoggingWorker) themselves have to extend a base | |
class (not `object`), because __init__ needs to accept parameters (otherwise | |
you get "TypeError: object.__init__() takes no parameters" | |
* Your base classes need to call super() to allow the other base classes to | |
continue propagating. For example if DBWorker fails to call super(), then | |
LoggingWorker's init function DOES NOT RUN. DBworker ends up halting the | |
propagation of init functions. | |
The execution order of __init__ functions: | |
1. MyWorker | |
2. DBWorker | |
3. LoggingWorker | |
4. BaseWorker | |
If any of the __init__ functions fails to call super(), execution halts and | |
doesn't continue to the next one in the list. | |
Script output: | |
My worker init | |
DBWorker init | |
DBworker config: develop | |
LoggingWorker init | |
LoggingWorker config: develop | |
WorkerBase init | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment