How to implement multiple constructors

tron.thomas at verizon.net tron.thomas at verizon.net
Sun May 8 18:05:15 EDT 2005


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?




More information about the Python-list mailing list