inherit without calling parent class constructor?

Christian Dieterich cdieterich at geosci.uchicago.edu
Wed Jan 26 12:29:48 EST 2005


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)

Here's a workaround:

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, object):
         for key, value in object.__dict__.iteritems():
             setattr(self, key, value)
         self.value = 1

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

Here's another workaround:

Bsize = 0
class B:
     def __init__(self, length):
         size = self.method(length)
         self.size = size
         global Bsize
         Bsize = self.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):
         self.size = Bsize
         self.value = 1

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




More information about the Python-list mailing list