python class methods identity?

Chris Mellon arkanes at gmail.com
Fri Nov 23 12:19:25 EST 2007


On Nov 23, 2007 1:29 AM, Roc Zhou <chowroc.z+l at gmail.com> wrote:
> Hello,
>
> I'm now being confused by this segment of code:
> >>> class Test:
> ...     var = 1
> ...     def func(self): pass
> ...
> >>> x = Test()
> >>> y = Test()
> >>> x.var is y.var
> True
> >>> x.func is y.func
> False
> >>> id(x.var); id(y.var)
> 146132400
> 146132400
> >>> id(x.func); id(y.func)
> -1208243388
> -1208243388
>
> Since both "var" and "func" are the variable of the class object, and

"members", not variables.

> x.var is y.var, why x.func is not y.func while their id() return the
> same value.
>

It's because of the descriptor lookup that turns functions into
methods. If you just print x.func and y.func on the console you'll see
that they're bound methods of a specific instance - not the unbound
method object you'd see if you look at Test.func.

Your id test is giving you misleading results because you aren't
storing the boundmethod between lookups - the objects have the same id
not because they are the same object, but because they're created one
after the other and are re-using the same memory block.



More information about the Python-list mailing list