Variable Modifications in a class

Alan Kennedy alanmk at hotmail.com
Tue Jun 3 13:29:41 EDT 2003


"Mehta, Anish" wrote:

> I am having a problem in tackling the variables in the class.
> 
> class AB:
>    def __init__(self):
>        self.a = None
>        self.b = None
> 
> def func(ab):
>    b = ab()
>    c = ab()
> 
>    b.a = 5
>    b.b = 10
> 
>    c = b
     ^^^^^

This is where you are misunderstanding python.

"b" and "c" are not variables, they are references. They are simply a name,
which is "bound" to something, so the name "refers to" the something.

So let's run through your function line by line

 def func(ab):
    b = ab()

This creates a new AB object, the first one.
It also creates the name "b", and binds it to the new AB object.

    c = ab()

This also creates a new (and different) AB object, the second one.
It also creates the name "c", and binds it to the second AB object.
 
    b.a = 5

Set the "a" member of the AB object *referred to* to by "b" to 5

    b.b = 10

Set the "b" member of the AB object *referred to* to by "b" to 10
 
    c = b

Make the name "c" refer to whatever "b" refers to
(in this case, the *first* AB object).
Note also that you now have no way of getting at the second AB 
object, since you have no reference to it. It has fallen into the
garbage heap, and will be recycled eventually.

   c.a = 30

Set the "a" member of the AB object referred to by c (i.e. the first AB
object) to 30

   c.b = 40

Set the "b" member of the AB object referred to by c (i.e. the first AB
object) to 40

I think you will understand the behaviour better now.

HTH,

-- 
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan:              http://xhaus.com/mailto/alan




More information about the Python-list mailing list