[Tutor] Tutor Digest, Vol 131, Issue 59 Order loop from methos on class (jarod_v6 at libero.it)

Dino Bektešević ljetibo at gmail.com
Mon Jan 26 12:41:19 CET 2015

> Message: 1
> Date: Mon, 26 Jan 2015 11:48:52 +0100 (CET)
> From: "jarod_v6 at libero.it" <jarod_v6 at libero.it>
> To: tutor at python.org
> Subject: [Tutor] order loop from methos on class
> Message-ID:
>         <2044122047.125321422269332108.JavaMail.defaultUser at defaultHost>
> Content-Type: text/plain; charset=UTF-8
> Dear All,
> What is the best way to loop on methos on a class?
> class Rna():
>     def trim():
>         ...
>     def align():
>         ...
> ena = Rna()
> ena.trim()
> ena.aling()
> Thanks for any suggestion!!!

Not quite sure where you're going with this, but to loop through the
methods of a class can be done and is dependent on the python

For py3:

class Rna():
    def trim():
    def align():

ena = Rna()

for method in dir(Rna):
    if method[:2] != "__":

the other way to do it is to:

for method in dir(Rna):
    if method[:2] != "__":
        getattr(ena, method)()

DO NOTICE HOW "WONKY" THIS IS. If you have a method that expects
input, or if you defined private methods (with __) this will either
skip them, or in worse case, if you cut out the if question, try to
call all the builtin methods (such as getattribute) and it will fail
because no proper input has been sent. This will only work for C style
"void" kind of methods.
Probably the best way to get them, though, do it is to:

import inspect

inspect.getmembers(Rna(), predicate=inspect.ismethod)

[('__init__', <bound method Rna.__init__ of <__main__.Rna object at
0x02E39E70>>), ('align', <bound method Rna.align of <__main__.Rna
object at 0x02E39E70>>), ('trim', <bound method Rna.trim of
<__main__.Rna object at 0x02E39E70>>)]

This gets you tuples of (name, reference) kind of deal you can run
through. This does help to weed out some of the builtin methods, but
__init__ (or possibly __new__ ?) will still show up. If you need the
builtins as well you can ask for inspect.isbuiltin.

In python2 the first way is not going to work for sure, I don't think
there exist a __getattribute__, but the 2nd way (getattr) and the
inpect module will.

I do wonder why do you need this though. I've only once run into a
situation where I did something similar and that was _ONLY_ because I
was too lazy to write up proper classes and decompose the problem, for
what at the time seemed like a simple test run, so I ended up reading
a lot of properties from a file and did not want to name all of them
myself in the code. I ended up paying the price and wrote all the
necessary classes because it was hard to debug....

Hopefully you'll think it through, don't be lazy it never pays off!
Best of luck,

More information about the Tutor mailing list