How to implement multiple constructors
James Stroud
jstroud at mbi.ucla.edu
Sun May 8 18:28:39 EDT 2005
On Sunday 08 May 2005 03:05 pm, tron.thomas at 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/
More information about the Python-list
mailing list