inherit without calling parent class constructor?

Steven Bethard steven.bethard at gmail.com
Wed Jan 26 12:46:45 EST 2005


Christian Dieterich wrote:
> Hi,
> 
> I need to create many instances of a class D that inherits from a class 
> B. Since the constructor of B is expensive I'd like to execute it only 
> if it's really unavoidable. Below is an example and two workarounds, but 
> I feel they are not really good solutions. Does somebody have any ideas 
> how to inherit the data attributes and the methods of a class without 
> calling it's constructor over and over again?
> 
> Thank,
> 
> Christian
> 
> Here's the "proper" example:
> 
> class B:
>     def __init__(self, length):
>         size = self.method(length)
>         self.size = size
>     def __str__(self):
>         return 'object size = ' + str(self.size)
>     def method(self, length):
>         print 'some expensive calculation'
>         return length
> 
> class D(B):
>     def __init__(self, length):
>         B.__init__(self, length)
>         self.value = 1
> 
> if __name__ == "__main__":
>     obj = D(7)
>     obj = D(7)

I'm confused as to how you can tell when it's avoidable...  Do you mean 
you don't want to call 'method' if you don't have to?  Could you make 
size a property, e.g.

class B(object):
     def __init__(self, length):
         self._length = length
     def _get_size(self):
         print 'some expensive calculation'
         return self._length
     size = property(fget=_get_size)

class D(B):
     def __init__(self, length):
         super(B, self).__init__(length)
         self.value = 1

if __name__ == "__main__":
     obj = D(7)
     obj = D(7)

Then 'size' won't be calculated until you actually use it.  If 'size' is 
only to be calculated once, you might also look at Scott David Daniels's 
lazy property recipe:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/363602

Steve



More information about the Python-list mailing list