constructing an object from another instance of the same class

Stephen Hansen me+list/python at ixokai.io
Fri Jun 18 11:34:43 EDT 2010


On 6/18/10 3:51 AM, Christoph Groth wrote:
> sometimes it is handy to have a function which can take as argument
> anything which can be converted into something, e.g.
[snip]
> I would like to mimic this behavior of float for a user-defined type,
> e.g. 
[snip]
> Now I wonder what is the most pythonic way to write the __init__ method
> of My_type?  The following comes to my mind:
[snip]
> 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.
[snip]
> 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.

This kind of polymorphism is anti-Pythonic; you don't go around
converting an object from one 'type' to another 'type' like that, and
especially not for that reason.

Basically, you're thinking about *types* too much. They are much less
important in Python then they are in C++; you achieve polymorphism in
Python by matching behavior and following the protocols of the other type.

Duck typing: if it quacks like a duck, its a duck.

The Pythonic way to approach the problem of, "I want to accept anything
which can be converted into X" is to accept the variable, and then
simply *use* it *as if* it were X. If the value implemented the
appropriate protocols (say, __add__ and __radd__ and friends and such if
you want it to mimic a numeric type) then it will work.

For all intents and purposes, it *is* X, for all you need to worry about.

If it doesn't implement the protocols, then it will error out, yes.
It'll throw an exception. You can be prepared to catch such exceptions
and say, log an error, "Expected value to be a numeric type", or you can
just let it propagate (I almost always prefer this method). Sometimes
you need to be a little more careful, sometimes less: but generally,
only at the boundry of your program do you need to worry about
type-correctness (i.e., where user and data is accepted, you have to
convert stuff there.) Anywhere else, its a bug if you pass the wrote
thing in: unit tests and exceptions/tracebacks are excellent for finding
and fixing such bugs.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 487 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20100618/66f5923e/attachment-0001.sig>


More information about the Python-list mailing list