Python 3K or Python 2.9?

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Sep 13 03:33:04 EDT 2007


TheFlyingDutchman a écrit :
> On Sep 12, 4:40 am, Bjoern Schliessmann <usenet-
> mail-0306.20.chr0n... at spamgourmet.com> wrote:
>> Ivan Voras wrote:
>>> What does "self" have to do with an object model? It's an
>>> function/method argument that might as well be hidden in the
>>> compiler without ever touching the role it has (if not, why?). I
>>> agree that it's needless noise in a language.
>> If this was needless, why do C++ and Java have the "this" pointer?
>>
> "this" in C++ and Java is not shown in the parameter list, which was
> what he was
> complaining about.  He wants
> 
> class MyClass:
>         def SomeFunction(someParameter):
>            self.someParameter = someParameter
> 
> not
> 
> class MyClass:
>         def SomeFunction(self, someParameter):
>            self.someParameter = someParameter
> 
> 
> The confusing way about the current Python method when you first
> encounter it is
>  why is "self" being passed in when you write the function

At this stage, it's not "passed in", it's declared in the arguments list.

> but not
> when you call it.

It *is* passed when you call the function.

> If the compiler is smart enough to know that

The compiler has absolutely nothing to do with it. It's the object model 
that takes care of this. Quick explanation:

- functions objects implement the descriptor protocol.
- when a function which is an attribute of a class is looked up on an 
instance of that class, the  __get__ method of the function object is 
called with the instance (and class) as arguments.
- this method returns a closure wrapping the instance, the class and the 
function object itself
- when this closure is called, it itself prepends the instance to the 
args it receives, calls the function with these args, and returns the 
result.

This is why you need tho declare the instance as the first argument, but 
don't need to pass it explicitely *when calling the function as a method 
of an object*. Notice that you can still use the function directly, 
passing the instance by yourself. And that you can define a function 
outside a class and then attach it to a class. To make a long story 
short, Python's methods are just thin temporary wrappers around plain 
functions.

>     a = MyClass()
>     a.SomeFunction(12)
> 
> SomeFunction() has a "self" implicitly added to the parameter list,  it
> seems that it should be smart enough to know that a function defined
> in a class has a "self" implicitly added to the parameter list.

The compiler has nothing to do with it, and where you define the 
function is totally orthogonal:

def truc(obj):
   print obj

class Toto(object):
   pass

Toto.trac = truc

t = Toto()
t.trac()




More information about the Python-list mailing list