overriding of methods and variables in a class.

Alex Martelli aleaxit at yahoo.com
Mon Jul 9 13:26:00 EDT 2001


<rdesetty at yahoo.com> wrote in message
news:mailman.994686374.24889.python-list at python.org...
> I dont seem to understand why a method name and a variable name is
> allowed to be same in a class. what is the use. Most importantly,

Identifiers obey the same rules, whether they identify function objects
or non-function objects.  No name becomes 'reserved' because it has
been bound to something else (except maybe in an _instance_ whose
class defines an appropriate __setattr__, but that doesn't apply here
and I won't keep harping on this tiny escape clause in the following).

In other words: a name (of a class attribute) that has been bound to
one thing can later be re-bound to some other thing.  When a name
that was bound to object X is later re-bound to object Y, it is NOT any
more bound to X, of course; the name is only bound to ONE object at
any given point in time, so a re-binding *takes the place* of the
previous binding.

> Assuming that we have a class as follows:
>
> class abc
> # I am going to define a variable here.
> var_x = 1

This binds name var_x in the namespace of class abc to object 1.  OK so far.

> # now the function with the same name as the variable with say some
> #parameter
> def var_x(abc)

This RE-binds name var_x in the namespace of class abc to another object.
So, the name var_x is not bound any more to the object (the number 1) it
was previously bound to.

>     return abc+1
>
> Now the question is how do i access the variable as well as the
> function (with the same name as the variable) say from another
> function. thanx in advance.

There is no 'variable' that is separate from the 'function' any more.
Class attribute abc.var_x is only bound to one object at any given
point in time.  In your example, it was bound to the number 1 for
a tiny moment, then immediately got re-bound to something else
(a function object -- which magically mutates into a method object
when you access it directly, but that's another issue).


Alex






More information about the Python-list mailing list