confused about self, why not a reserved word?
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Mon May 5 10:38:58 EDT 2008
globalrev a écrit :
> sorry i noticed now a little error, i was playing around a lot and saw
> that on the sel-example i had then called foo.hello() instead of
> foo.Hello().
>
>
> but it was an informing error now i egt it. was wondering about self
> anyway so thanks for clearing it up.
>
>
> but it still is a bit confusing that u can pass with any word.
> wouldnt:
>
>
> class Foo(object):
> def Hello():
> print "hi"
>
>
> make more sense?
What would make sens in your example would be to either make hello a
staticmethod, since it doesn't use any reference to the current instance
nor it's class.
> the class-thing seems inside out somehow in python.
Python's object model is indeed a bit pecular wrt/ most mainstream
OOPLs. But once you understand how it works, it happens to be mostly
well designed (IMHO) and really powerful.
> if im doing
> foo.Hello() im already saying that im using the class foo because i
> did foo=Foo()
Nope. You are saying your using an instance of class Foo.
> before and then still when calling Hello() i am
> invisibly passing the class itself a s a parameter by default?
It's not the class that get passed (unless you use a classmethod, but
that's not the case here), but the instance. And you are not "invisibly"
passing it, you just pass it another way. In fact, foo.hello() is
equivalent to type(foo).hello(foo).
> just seems backwards and weird.
Each and every OOPL needs to have a way to "inject" the instance a
method was called on into the method's local namespace. Python solved
this it's own way - by making 'methods' thin wrappers around
instance/function couples, these wrappers being in charge of calling the
function with the instance as first argument. From the implementation
POV, this allow to build methods on existing, more general features -
functions and the descriptor protocol - instead of having to
special-case them. From the programmer's POV, this allow to define
functions outside classes, then dynamically add them as 'methods' either
on a per-class or per-instance basis.
More information about the Python-list
mailing list