inherit without calling parent class constructor?
From: Christian Dieterich (cdieterich_at_geosci.uchicago.edu)
Date: 01/26/05
- Next message: Evan Simpson: "Subclassed dict as globals"
- Previous message: Stephen Kellett: "Re: is there better 32 clock() timing?"
- Next in thread: Steven Bethard: "Re: inherit without calling parent class constructor?"
- Reply: Steven Bethard: "Re: inherit without calling parent class constructor?"
- Reply: Daniel Dittmar: "Re: inherit without calling parent class constructor?"
- Reply: Jeff Shannon: "Re: inherit without calling parent class constructor?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 26 Jan 2005 11:29:48 -0600 To: python-list@python.org
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)
- Next message: Evan Simpson: "Subclassed dict as globals"
- Previous message: Stephen Kellett: "Re: is there better 32 clock() timing?"
- Next in thread: Steven Bethard: "Re: inherit without calling parent class constructor?"
- Reply: Steven Bethard: "Re: inherit without calling parent class constructor?"
- Reply: Daniel Dittmar: "Re: inherit without calling parent class constructor?"
- Reply: Jeff Shannon: "Re: inherit without calling parent class constructor?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|