Nice way to cast a homogeneous tuple
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Wed Jul 28 10:32:22 EDT 2010
On Wed, 28 Jul 2010 09:35:52 -0400, wheres pythonmonks wrote:
> Thanks ... I thought int was a type-cast (like in C++) so I assumed I
> couldn't reference it.
Python doesn't have type-casts in the sense of "tell the compiler to
treat object of type A as type B instead". The closest Python has to that
is that if you have an instance of class A, you can do this:
a = A() # make an instance of class A
a.__class__ = B # tell it that it's now class B
and hope that it won't explode when you try to use it :/
I make that seem like a dangerous thing to do, but it's not really. There
actually are sensible use-cases for such a thing, you can't do it to
built-ins (which would be dangerous!), and the worst that will happen
with classes written in Python is they'll raise an exception when you try
calling a method, rather than dump core.
Otherwise, all type conversions in Python create a new instance of the
new type, and the conversion functions themselves (int, str, etc.) are
actual type objects which you can pass around to functions:
>>> type(int)
<type 'type'>
Calling int(x) calls the int constructor with argument x, and returns a
new int object. (In the *specific* case of int, it will sometimes cache
small integers and re-use the same one multiple times, but don't count on
that behaviour since it's an implementation-specific optimization.)
--
Steven
More information about the Python-list
mailing list