Python variables are bound to types when used?
Diez B. Roggisch
deets at nospam.web.de
Fri Oct 21 15:20:32 EDT 2005
sjdevnull at yahoo.com wrote:
> Fredrik Lundh wrote:
>
>>reset your brain:
>>
>> http://effbot.org/zone/python-objects.htm
>
>
> Neat link.
>
> Can you expand on this:
>
>
>>a type (returned by type(x))
>
> ...
>
>>You cannot change the type.
>
>
> Especially what's going on here:
>
>
>>>>class a(object):
>
> ... pass
> ...
>
>>>>class b(a):
>
> ... pass
> ...
>
>>>>x=b()
>>>>x.attr=1
>>>>type(x)
>
> <class '__main__.b'>
>
>>>>type(y)
>
> <class '__main__.b'>
>
>>>>x.__class__=a
>>>>type(x)
>
> <class '__main__.a'>
>
>>>>x.attr
>
> 1
>
> It looks to me like x is still referencing the same object (and still
> has the "attr" attribute) but its type has changed. Is that not right?
So what? That the flexibility of python allows for such a hack has
nothing to do with x being totally unaware of the type of the object it
points to.
You only access values by names pointing/refering to them. If they are
mutable, you can mutate them. If not (like strings, ints and floats),
you have to rebind the name with a new value. But none of these changes
what x is - and what not. Its a name, pointing to a value, and knows
nothing about what it is actually bound to.
Regards,
Diez
More information about the Python-list
mailing list