who to call a list of method inside the class itself

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Aug 20 02:14:00 EDT 2008


En Tue, 19 Aug 2008 11:18:00 -0300, <maduma at pt.lu> escribi�:

> Is the following code is ok. who to call all method.
> It is working but the call to m() without a reference to self seems
> strange

Ok, so you already know it works - and you want to know why!

> class CustomMethod:
>     def method1(self):
>         ....
>     def method2(self):
>         ....
>     def method3(self):
>        ....
>
>     def getAllMethod(self):
>         return [self.method1, self.method2, self.method3]
>
>     def applyAll(self):
>         for m in self.getAllMethod():
>             # how to call all methods ?
>             # is it correct
>             m()

When you write self.method1, you get a "bound method" - it already knows  
the instance on which it is called (self, in this case).
When you write CustomMethod.method1, you get an "unbound method" - it is  
not bound to any particular instance; you must provide the instance  
yourself when calling it.
See "User-defined methods" in http://docs.python.org/ref/types.html - if  
you really want to know how this works, read about  new-style classes and  
the descriptor protocol at http://www.python.org/doc/newstyle/

-- 
Gabriel Genellina




More information about the Python-list mailing list