An interesting python problem

bruno modulix onurb at xiludom.gro
Wed Sep 14 05:03:26 EDT 2005


Johnny Lee wrote:
> Hi,
>    Look at the follow command in python command line, See what's
> interesting?:)
> 
> 
>>>>class A:
> 
> 	i = 0
> 
>>>>a = A()
>>>>b = A()
>>>>a.i = 1
>>>>print a.i, b.i
> 
> 1 0

Quite what I would expect. First you declare i as being a *class*
attribute of A, with value 0. Then you create 2 instances a and b of A.
Then you add to a an *instance* variable named i (that then shadows the
class variable of the same name), with value 1. Then you print a.i,
wihci is the instance variable i of a, and b.i, which is the class
variable i of A, with value 0.

> ---------------------------------------
> 
> 
>>>>class A:
> 
> 	arr = []
> 
>>>>a = A()
>>>>b = A()
>>>>a
> 
> <__main__.A instance at 0x00C96698>
> 
>>>>b
> 
> <__main__.A instance at 0x00CA0760>
> 
>>>>A
> 
> <class __main__.A at 0x00B314B0>
> 
>>>>a.arr.append("haha")
>>>>print a.arr , b.arr
> 
> ['haha'] ['haha']

Now you create a class A with a *class* variable arr which is an empty
list, and 2 instances a and b of A. Then you append to a.arr - which is
A.arr, so when you print a.arr and b.arr, you in fact print A.arr

>>>>a.arr = ["xixi"]

Then you add an instance variable arr to a, shadowing A.arr

>>>>print a.arr , b.arr
> 
> ['xixi'] ['haha']

So now you print a.arr and A.arr (accessed thru b)

(snip)


> 
>>>>class X:
> 
> 	def __init__(self):
> 		self.arr = []
> 
>>>>m = X()
>>>>n = X()
>>>>m.arr.append("haha")
>>>>print m.arr, n.arr
> 
> ['haha'] []
> 

Here you define a class X with an *instance* variable arr, and two
instances m and n of X, then append to m.arr, which of course has no
impact on n.

I dont see anything interesting nor problematic here. If you understand
the difference between class attributes and instance attributes, the
difference between mutating an object and rebinding a name, and the
attribute lookup rules in Python, you'll find that all this is the
normal and expected behavior.

Or did I miss something ?

-- 
bruno desthuilliers - is Python much more readable than Perl ???
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list