constructing an object from another instance of the same class

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Jun 21 05:38:06 EDT 2010


Christoph Groth wrote:
> Dear all,
>
> sometimes it is handy to have a function which can take as argument
> anything which can be converted into something, e.g.
>
> def foo(arg):
>     arg = float(arg)
>     # ...
>
> I would like to mimic this behavior of float for a user-defined type,
> e.g. 
>
> def bar(arg):
>     arg = My_type(arg)
>     # ...
>
> Now I wonder what is the most pythonic way to write the __init__ method
> of My_type?  The following comes to my mind:
>
> class My_type:
>     def __init__(self, other):
>         if isinstance(other, type(self)):
>             self.a = other.a
>             self.b = other.b
>             return
>         # initialize self in some other way
>
> It seems to me that in this way I might get problems when I pass an
> instance of Derived_from_my_type to bar, as it will become an instance
> of My_type.
>
> What is a good way to express this?  In C++ (which I know better than
> python) I would make bar accept a const reference to My_type.  Then I
> could use it directly with instances of My_type, Derived_from_my_type
> and other types which can be converted into My_type.
>
> thanks
> Christoph
>
>   
There is no need to do such thing in python most of the time. Python is 
strongly typed and won't change the type of an object for you (unlike 
perl for instance). That means no matter where you are in your code, you 
should know the exact type of your objects.

If you don't, that means you are assigning to the *same name*, object of 
different types. You don't want to that.

One possible solution is to make your class also a factory class:
python 2.5

class My_type(object):
    @classmethod
    def fromInt(cls, anInteger):
       """Return a My_type instance given an integer"""
       pass

    @classmethod
    def fromString(cls, aString):
       """Return a My_type instance given an integer"""
       pass


Try to resist the temptation of making one constructor that would handle 
any type of parameter, it may look stylish,  but from the "I don't care 
about the parameter type" you will soon experience the "I don't know 
about the parameter type" which is problematic when debugging / 
maintaining the code.

JM



More information about the Python-list mailing list