who to call a list of method inside the class itself

Terry Reedy tjreedy at udel.edu
Tue Aug 19 17:48:22 EDT 2008


  maduma at pt.lu wrote:
> 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

The reference to self is bound to the methods by the way you look them up.


> 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():
>             m()

If the list is static, there is no need to calculate it more than once, 
at class-definition time.  I might do this like so:

class CustomMethod:
...
     all_methods = [method1, method2, method3]
     def apply_all(self):
         for m in self.all_methods:
             m(self)

Class code has access to the results of previous class code.

tjr




More information about the Python-list mailing list