473,413 Members | 1,833 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,413 software developers and data experts.

How to implement multiple constructors

I am a C++ developer with only a little experience using Python. I
want to create a Python class where by I can construct an instance from
that class based on one of two different object types.

For example, if I were programming in C++, I would do the something
like the following:

class MyClass
{
public:
MyClass(const SomeType& type);
MyClass(const SomeOtherType& type);
....
};

In Python I cannot have two constructors that each take a single
argument as Python does not distinguish the type of objects that are
passed to functions.

One thought I had was to use the isinstance method such as this:

class MyClass:
__init__(self, object):
if isinstance(object, SomeType):
#Initialize based on SomeType object
...

elif isinstance(object, SomeOtherType):
#Initialize base on SomeOtherType object
...

else:
#Raise some kind of exception
...

Some research I've done on the Internet indicates that the use of the
isinstance method can be problematic, and I'm not sure if it is the
best approach to solving my problem.

What is the best way for me to implement this type of functionality in
Python?

Jul 19 '05 #1
5 1798
tr*********@verizon.net wrote:
I am a C++ developer with only a little experience using Python. I
want to create a Python class where by I can construct an instance from
that class based on one of two different object types.

For example, if I were programming in C++, I would do the something
like the following:

class MyClass
{
public:
MyClass(const SomeType& type);
MyClass(const SomeOtherType& type);
...
};


How about using a classmethod as an alternate constructor:

py> class C(object):
.... def __init__(self, i):
.... self.i = i
.... @classmethod
.... def fromstr(cls, s):
.... return cls(int(s))
....
py> C(1).i
1
py> C.fromstr('2').i
2

STeVe
Jul 19 '05 #2
On Sunday 08 May 2005 03:05 pm, tr*********@verizon.net wrote:
I am a C++ developer with only a little experience using Python. I
want to create a Python class where by I can construct an instance from
that class based on one of two different object types.

For example, if I were programming in C++, I would do the something
like the following:

class MyClass
{
public:
MyClass(const SomeType& type);
MyClass(const SomeOtherType& type);
...
};

In Python I cannot have two constructors that each take a single
argument as Python does not distinguish the type of objects that are
passed to functions.

One thought I had was to use the isinstance method such as this:

class MyClass:
__init__(self, object):
if isinstance(object, SomeType):
#Initialize based on SomeType object
...

elif isinstance(object, SomeOtherType):
#Initialize base on SomeOtherType object
...

else:
#Raise some kind of exception
... Some research I've done on the Internet indicates that the use of the
isinstance method can be problematic, and I'm not sure if it is the
best approach to solving my problem.

What is the best way for me to implement this type of functionality in
Python?


In case you haven't found it: <http://www.canonical.org/~kragen/isinstance/>

Can both of these classes (be modified to/subclassed to) support the same
interface such that MyClass.__init__ will not care which is passed? I believe
this would be the best solution (read: "my favorite solution"). If you know
what type of object "object" is (BTW, a keyword in 2.3 and later, I believe),
then one approach is to initialize with a blank MyClass instance and use
"fill_with_SomeType()" and "fill_with_SomeOtherType()" methods.

I think the least elegant approach is to test for interface compatibility,
e.g.:

try:
self.avalue = isinstance.get_avalue()
except NameError:
self.avalue = isinstance.get_anothervalue()

But this may get out of hand with many different possibilites.

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 19 '05 #3
On Sunday 08 May 2005 03:28 pm, James Stroud wrote:
* *try:
* * *self.avalue = isinstance.get_avalue()
* *except NameError:
* * *self.avalue = isinstance.get_anothervalue()


I have no idea where I copied those "isinstance"s from. Also, the except
should be an AttributeError. Here is a retry:

* *try:
* * *self.avalue = aninstance.get_avalue()
* *except AttributeError:
* * *self.avalue = aninstance.get_anothervalue()

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 19 '05 #4
tr*********@verizon.net wrote:
I am a C++ developer with only a little experience using Python. I
want to create a Python class where by I can construct an instance from
that class based on one of two different object types.


The approaches I've seen used are to use a new class method as an
alternate ctor with a special name, and to use the types module for type
comparison within such a ctor.

--
J C Lawrence They said, "You have a blue guitar,
---------(*) You do not play things as they are."
cl**@kanga.nu The man replied, "Things as they are
http://www.kanga.nu/~claw/ Are changed upon the blue guitar."
Jul 19 '05 #5
James Stroud wrote:
If you know what type of object "object" is
(BTW, a keyword in 2.3 and later, I believe)


Not a keyword, but a builtin as of 2.2.

STeVe
Jul 19 '05 #6

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

Similar topics

12
by: Philip Smith | last post by:
Call this a C++ programmers hang-up if you like. I don't seem to be able to define multiple versions of __init__ in my matrix class (ie to initialise either from a list of values or from 2...
4
by: Jimmy Johns | last post by:
Hi, I have some classes as follows: #include <iostream> using namespace std; class A { public: virtual A* clone() const = 0; };
5
by: Glen Able | last post by:
Any ideas why compilers seem to give warnings about multiple copy constructors e.g. class A { public: A(A& a); A(const A& a); };
2
by: Neil Zanella | last post by:
Hello, AFAIK the only way to initialize a reference variable defined inside a class is to initialize it in an initializer list. However, when there are multiple constructors, this means that the...
2
by: Mark | last post by:
public class myClass { public myClass(string param1) { //HOW DO I CALL myClass() below?? myClass(); // THIS DOES NOT WORK } public myClass() {
7
by: andrewfsears | last post by:
I have a question: I was wondering if it is possible to simulate the multiple constructors, like in Java (yes, I know that the languages are completely different)? Let's say that I have a class...
7
by: Adam Nielsen | last post by:
Hi everyone, I'm having some trouble getting the correct chain of constructors to be called when creating an object at the bottom of a hierarchy. Have a look at the code below - the inheritance...
3
by: Jess | last post by:
Hello, I've been reading Effective C++ about multiple inheritance, but I still have a few questions. Can someone give me some help please? First, it is said that if virtual inheritance is...
5
by: Weihui Shen | last post by:
Hello. Sometimes I see that some class constructors were implemented with assignment operator and I wanna know whether it is safe to do that or not?
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.