class func & var name overlap

Steve Holden sholden at holdenweb.com
Sat Mar 10 00:39:04 EST 2001


I've added a few comments which might make things plainer.

"Changsen Xu" <xu.20 at nd.edu> wrote in message
news:3AA9AEC2.12BA1E95 at nd.edu...
> hi all,
>
> I just now tried function name and variable name overlaping
> in Python's script (1) and (2):
>
> (1)
> class x:
>         x = 3                        # bind x to 3
>         def x(self): return 5    # bind x to a function that returns 5
> y=x()                                # bind y to an instance of class x
> print y.x                            # print the x (instance method) of y
>
>
> (2)
> class x:
>         x = 3                        # bind x to 3
>         def x(self): return 5    # bind x to a function that returns 5
>         x = 6                        # bind x to 6
> y=x()                                # bind y to an instance of class x
> print y.x                            # print the x (class variable) of y
>
>
> Then if I run 1), I got screen echo as
>         <method x.x of x instance at 80e17d4>

Correct. The "def" statement assigns the function body (and the function is
an instance method) to the function name. This behavior is competely
dynamic, because def is an executable statement. So you can define the same
function several times, and the last definition befoer the call is the one
which gets called.

> while for 2), I got
>         6
>

Correct. In this case you are referring to a name which was assigned during
the class definition. Like def, class is an executable statement, and names
(whether of methods or simple variables) bound during the definition are
associated with the class. In looking for attributes of an instance Python
looks in the class definition if it doesn't find it in the instance. If ti
doesn't find it there, it looks in the superclass, and so on. So you get the
last value assigned to the class variable.

> I'm here curious why Python doesn't even report an error
> for this obvious mistake ?
>
That's because it's not a mistake. It's perfectly legitimate to bind
functions to several names.

Hope his helps.

regards
 Steve






More information about the Python-list mailing list