inheritance problem with 2 cooperative methods

Dan Perl danperl at rogers.com
Fri Dec 3 13:56:29 CET 2004


This is almost the same code as Greg's with the only difference being that 
test for configuration having been done.  But the test is unnecessary.  I 
don't see how setConfig could be invoked in the super of the base class (A), 
so such a test would be relevant only in subclasses, if they DO invoke 
setConfig.  But it's better if they just don't invoke it, which makes for a 
much cleaner solution.  Thanks anyway.

BTW, you named the attribute configinitialized in one place and configSet in 
the other place.  Which proves that the test is redundant, because it does 
work anyway as is.

I had a similar solution, where I was invoking setConfig only if the class 
of self is the same as the class where __init__ is defined, something like 
this:
class A (object):
    def __init__(self, config):
       self.x = 0
       super(A, self).__init__()
       if A == self.__class__:
         self.setConfig(config)

I didn't like it though because it has to be done like this in every 
subclass's __init__.  And it's a problem that I didn't realize at the time 
if a subclass just does not need to override __init__ (then the 
configuration is just not set).

Dan

"David Fraser" <davidf at sjsoft.com> wrote in message 
news:copb1o$ncv$1 at ctb-nnrp2.saix.net...
>
> What about using an attribute in the base class to remember whether 
> initial config has been done? This seems to work:
>
> #!/usr/bin/python
> class A (object):
>    def __init__(self, config):
>       self.x = 0
>       self.configinitialized = False
>       super(A, self).__init__()
>       if not self.configinitialized:
>         self.setConfig(config)
>    def setConfig(self, config):
>       self.x += config['x']
>       self.configset = True
>
> class B (A):
>    def __init__(self, config):
>       self.y = 0
>       super(B, self).__init__(config)
>    def setConfig(self, config):
>       super(B, self).setConfig(config)
>       self.y += config['y']
>
> class C (B):
>    def __init__(self, config):
>       self.z = 0
>       super(C, self).__init__(config)
>    def setConfig(self, config):
>       super(C, self).setConfig(config)
>       self.z += config['z']
>
> config = {'x':1, 'y':2, 'z':3}
> alpha = A(config)
> print alpha.x
> beta = B(config)
> print beta.x, beta.y
> beta.setConfig(config)
> print beta.x, beta.y
> gamma = C(config)
> print gamma.x, gamma.y, gamma.z
> gamma.setConfig(config)
> print gamma.x, gamma.y, gamma.z 





More information about the Python-list mailing list