[Tutor] Java style assignments in Python
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Wed Sep 10 12:58:51 EDT 2003
Hi Tpc,
> tpc at csua.berkeley.edu wrote:
>
> > hi Zak, well I was more familiar with Java's strong typing that I
> > assumed Python allowed assignment of a type to three variables.
(Small rant: I feel that Java's type system is a lot more trouble than
it's worth. OCaml, now that's a language that has strong typing. Mark
Jason Dominus has written a nice article that talks about type systems
here: http://perl.plover.com/yak/typing/typing.html.)
> Python has fairly strong typing too, but the type belongs to the object,
> *not* to the variable name that is bound to it.
yes. Whenever we're saying the expression:
[]
we're actually constructing an empty list --- in Java, we might say:
new ArrayList()
for a similar effect.
If we try something like this:
a = b = c = []
Then the analogous Java code looks like this:
Object a, b, c;
a = b = c = new ArrayList();
The important part to see in this Java pseudocode is that each variable
name is of type Object --- and this is pretty much the situation in
Python! Every name in Python is of a base type "PyObject", and the values
themselves contain runtime type information.
In fact, every method call we make on a value is looked up at runtime; we
can see this by co-opting the __getattr__() method:
###
>>> class WrapObject:
... def __init__(self, obj):
... self.obj = obj
... def __getattr__(self, attr):
... print "Intercepted call for attribute", attr
... return getattr(self.obj, attr)
...
>>> s = WrapObject([])
>>> s.append
Intercepted call for attribute append
<built-in method append of list object at 0x8157c8c>
>>> s.extend([4, 5, 6])
Intercepted call for attribute extend
>>> s
Intercepted call for attribute __repr__
[4, 5, 6]
>>> print s
Intercepted call for attribute __str__
[4, 5, 6]
>>>
>>>
>>> a, b = WrapObject(5), WrapObject(6)
>>> a + b
Intercepted call for attribute __coerce__
Intercepted call for attribute __add__
Intercepted call for attribute __coerce__
Intercepted call for attribute __radd__
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand types for +: 'instance' and 'instance'
###
(Hmmm! I wonder why there's a leading space when I did 'print s'. I'll
have to look into that sometime... *grin*)
Hope this helps!
More information about the Tutor
mailing list