473,386 Members | 1,706 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 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 3114
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?
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.