> Message: 1 > Date: Mon, 26 Jan 2015 11:48:52 +0100 (CET) > From: "jarod...@libero.it" <jarod...@libero.it> > To: tutor@python.org > Subject: [Tutor] order loop from methos on class > Message-ID: > <2044122047.125321422269332108.JavaMail.defaultUser@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 version... For py3: class Rna(): def trim(): print(1) def align(): print(2) ena = Rna() for method in dir(Rna): if method[:2] != "__": ena.__getattribute__(method)() 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, Dino _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor