iteration over methods
Bengt Richter
bokr at oz.net
Tue Jan 7 10:31:48 EST 2003
On Tue, 07 Jan 2003 13:12:12 +0100, Oliver Vecernik <vecernik at aon.at> wrote:
>Padraig Brady schrieb:
>> How about:
>>
>> class Someclass:
>> def __init__(self):
>> pass
>> def method1(self):
>> pass
>> def method2(self):
>> pass
>> def runallmethods(self):
>> for name, func in self.__class__.__dict__.items():
This limits search to the particular class dict, unlike dir(self)
See below.
>> if name[0:6] == 'method':
>> func(self)
>
>Well, I just see:
>
>__module__
>__doc__
>__init__
>
>But I didn't tell the whole story. Actually this class is subclassed:
>
>class Subclass(Someclass):
> def __init__(self):
> pass
>...
>
>def main():
> ref = Subclass
^- need () to make instance
> ref.runallmethods()
>...
>
>All other methods are inherited from 'Someclass'. Sometimes 'Subclass'
>may overload some methods, but in general they should be inherited. Is
>there also a possiblity to iterate over all of them?
>
There might be some hole in this, but it seems to work:
(BTW I added a method to the subclass, to show that
that gets picked up too).
If the
getattr(self, name)()
below seems cryptic, it's short for
func = getattr(self, name) # get bound method
func() # bound method call doesn't need self arg
====< OliverVercernik.py >===================
class Someclass:
def __init__(self):
pass
def method1(self):
print 'Hi from method1'
def method2(self):
print 'Hi from method2'
def runallmethods(self):
# for name, func in self.__class__.__dict__.items():
for name in dir(self):
if name[0:6] == 'method':
getattr(self, name)()
class Subclass(Someclass):
def __init__(self):
pass
def method_of_subclass(self):
print 'Hi from method_of_subclass'
def main():
ref = Subclass()
ref.runallmethods()
if __name__ == '__main__':
main()
=============================================
When run, it outputs:
[ 7:35] C:\pywk\clp>OliverVercernik.py
Hi from method1
Hi from method2
Hi from method_of_subclass
Regards,
Bengt Richter
More information about the Python-list
mailing list