Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/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
You can’t perform that action at this time.