How to implement multiple constructors

Steven Bethard steven.bethard at gmail.com
Sun May 8 18:21:57 EDT 2005


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);
> ...
> };

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



More information about the Python-list mailing list