iteration over methods
Giles Brown
giles_brown at hotmail.com
Tue Jan 7 15:33:11 EST 2003
Oliver Vecernik <vecernik at aon.at> wrote in message news:<3E1AB7B3.4050404 at aon.at>...
> Hi!
>
> I've got an object with some methods:
>
> class Someclass(self):
> def __init__(self):
> pass
> def method1(self):
> pass
> def method2(self):
> pass
> ...
> def runallmethods(self):
> for func in dir(self):
> if func[0:4] == 'method':
> apply(self.func) # Does *not* work!
>
> I'd like to run all methods named 'method...' in a sequence. Has anybody
> a clue how to achive this?
As an alternative to dir() you could use the inspect module:
import inspect
class Someclass:
def __init__(self):
pass
def method1(self):
print "called method1"
def method2(self):
print "called method2"
def runallmethods(self):
for name, method in inspect.getmembers(self, inspect.ismethod):
if name[:6] == 'method':
method.im_func(self)
class Derived(Someclass):
def method2(self):
print "called derived method2"
def method3(self):
print "called method3"
x = Derived()
x.runallmethods()
More information about the Python-list
mailing list