Calling every method of an object from __init__

Tim Chase python.list at tim.thechases.com
Mon Jun 19 16:22:10 EDT 2006


> Is there a simple way to call every method of an object from its
> __init__()?
> 
> For example, given the following class, what would I replace the
> comment line in __init__() with to result in both methods being called?
> I understand that I could just call each method by name but I'm looking
> for a mechanism to avoid this.
> 
> class Foo(object):
>     def __init__(self):
>         #call all methods here
>     def test(self):
>         print 'The test method'
>     def hello(self):
>         print 'Hello user'

 >>> class Foo(object):
...     def __init__(self):
...             for method in dir(self):
...                     if method == method.strip("_"):
...				f = getattr(self, method)
...				if callable(f): f()
...     def test(self):
...             print "in test..."
...     def hello(self):
...             print "in hello..."
...
 >>> x = Foo()
in hello...
in test...


This does assume that the method's signature takes no parameters 
and that you don't want to try and call "special" methods such as 
__add__ or "private" methods (usually indicated by leading 
underscores too) while you're going through the available methods.

-tkc







More information about the Python-list mailing list