OOP / language design question

bruno at modulix onurb at xiludom.gro
Tue Apr 25 10:56:20 EDT 2006


Duncan Booth wrote:
> bruno at modulix wrote:
> 
> 
>>Duncan Booth wrote:
>>(snip)
>>
>>>Usually though, if a subclass doesn't immediately call the base class
>>>constructors as the first thing it does in __init__ it indicates poor
>>>code and should be refactored.
>>
>>Not necessarily. It's a common case to have some computations to
>>do/some attributes to set in the derived class's __init__ before
>>calling the superclass's.
>>
> 
> 
> I did only say 'usually'. Can you actually think of any good examples where 
> you have to set a derived attribute before you can call the base class 
> constructor? 

class Base(object):
  def __init__(self, arg1):
    self.attr1 = arg1
    self.dothis()

  def dothis(self):
    return self.attr1

class Derived(Base):
  def __init__(self, arg1, arg2=0):
    self.attr2 = arg2
    Base.__init__(self, arg1)

  def dothis(self):
    return self.attr1 + self.attr2

(snip)

> Perhaps if the base __init__ calls an overridden 
> method, but at that point it sounds to me like something wants refactoring.

Why so ? This is a well-known pattern (template method). I don't see
what's wrong with it.

> I can think that you might have to do some computations to calculate 
> parameters for the base __init__, but that is a separate issue.


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list