constructing an object from another instance of the same class
Christoph Groth
cwg at falma.de
Fri Jun 18 06:51:39 EDT 2010
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
More information about the Python-list
mailing list