472,811 Members | 1,106 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,811 software developers and data experts.

inherit without calling parent class constructor?

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)

Jul 18 '05 #1
3 3084
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/Coo.../Recipe/363602

Steve
Jul 18 '05 #2
Christian Dieterich wrote:
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?


- rename B to A
- class B (A)
- move the costly constructor from A to B
- class D (A)

You can now move some parts from B.__init__ to A.__init__ if they are
really needed by D as well.

In OO speak: D is not really a subclass of B. Refactor the common code
into a new class A.

Daniel
Jul 18 '05 #3
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?


You could try making D a container for B instead of a subclass:

class D(object):
def __init__(self, ...):
self._B = None
def __getattr__(self, attr):
if self._B is None:
self._B = B()
return getattr(self._B, attr)

Include something similar for __setattr__(), and you should be in
business.

If it will work for numerous D instances to share a single B instance
(as one of your workarounds suggests), then you can give D's
__init__() a B parameter that defaults to None.

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: lawrence | last post by:
Is this a valid class definition? class McBase { // 06-14-04 - I may or may not later add something here. This will // be the top of the PDS content management system hierarchy. I'm //...
5
by: DarkSpy | last post by:
code here: struct A { int _i, _j; A() { cout<<"call default ctor"<<endl; } A(int i, int j) : _i(i), _j(j) { cout<<"call paramater ctor"<<endl; } };
5
by: Suzanne Vogel | last post by:
Hi, Given: I have a class with protected or private data members, some of them without accessor methods. It's someone else's class, so I can't change it. (eg, I can't add accessor methods to the...
2
by: William Payne | last post by:
Hello, consider these following two classes. A base class, class MDIChildWindow, and a class inherting from that base class, class Document. In the static base member function callback() I obtain a...
1
by: Xarky | last post by:
Hi, Having the following scenario: public class Parent { private string Parent_name; public Parent() { this.Parent_name = "";
6
by: Mohammad-Reza | last post by:
I wrote a component using class library wizard. In my component i want to in order to RightToLeft property do some works. I can find out if user set this property to Yes or No, But if He/She set it...
5
by: ffrugone | last post by:
My scenario involves two classes and a database. I have the classes "Broom" and "Closet". I want to use a static method from the "Closet" class to search the database for a matching "Broom". If...
19
by: zzw8206262001 | last post by:
Hi,I find a way to make javescript more like c++ or pyhon There is the sample code: function Father(self) //every contructor may have "self" argument { self=self?self:this; ...
1
by: DaTurk | last post by:
What's the syntax for calling a parent constructor in CLI?
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
How does React native implement an English player?
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.