I have following class inheritance schema:
object <- A <- B <- Z
Now each class will have public setup()
method, which calls other "private" method _configure()
, which contains loading code that I don't want to clutter up setup()
. The point is to make every class "know" how to set itself up, and do it before other executions.
So what I want when calling setup on Z's instance is to run both A's setup and B's setup (order is not particularly important now), while each setup using _configure as defined in its own class.
Now following script
#!/usr/bin/python
class A(object):
def __init__(self):
self.configured = []
self.set_up = []
def _configure(self):
self.configured.append("A")
def setup(self):
self._configure() # calls B._configure()!
self.set_up.append("A")
class B(A):
def _configure(self):
self.configured.append("B")
def setup(self):
super(B, self).setup()
self._configure()
self.set_up.append("B")
class Z(B):
pass
if __name__ == "__main__":
z = Z()
z.setup()
print "configured: %s" % z.configured
print "set up: %s" % z.set_up
runs B._configure()
twice, therefore returns
me@here:~$ ./t.py
configured: ['B', 'B']
set up: ['A', 'B']
me@here:~$
instead of configured: ['A', 'B']...
.
Could somebody explain this to me? How should I make sure that A.setup
calls A._configure
?
Workaround: What worked for now was replacing self._configure
with A._configure(self)
, but that seems ugly and non-OOP: now each class that could be potentially inherited should repeat its name with every method call? Where is the beauty and brevity of self
?