Calling every method of an object from __init__

John Machin sjmachin at lexicon.net
Mon Jun 19 16:44:47 EDT 2006


On 20/06/2006 5:55 AM, Rob Cowie wrote:
> Hi all,
> 
> 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'
> 

=== question ===

Why? What is the use case for a class *all* of whose methods can be 
called blindly from the __init__()?

=== code ===

class Foo(object):
     def __init__(self):
         #call all methods here
         for x in dir(self):
             if not x.startswith("__"):
                 method = getattr(self, x)
                 if callable(method):
                     print x, type(method), repr(method)
                     method()
     def test(self):
         print 'The test method'
     def hello(self):
         print 'Hello user'
     def variablenumberofargsohbuggerbacktothedrawingboard(self, arg1, 
arg2):
         print 'The unseen message'

obj = Foo()

=== output ===

hello <type 'instancemethod'> <bound method Foo.hello of <__main__.Foo 
object at 0x00AE2B70>>
Hello user
test <type 'instancemethod'> <bound method Foo.test of <__main__.Foo 
object at 0x00AE2B70>>
The test method
variablenumberofargsohbuggerbacktothedrawingboard <type 
'instancemethod'> <bound method 
Foo.variablenumberofargsohbuggerbacktothedrawingboard of <__main__.Foo 
object at 0x00AE2B70>>
Traceback (most recent call last):
   File "C:\junk\cowie.py", line 17, in ?
     obj = Foo()
   File "C:\junk\cowie.py", line 9, in __init__
     method()
TypeError: variablenumberofargsohbuggerbacktothedrawingboard() takes 
exactly 3 arguments (1 given)

Cheers,
John



More information about the Python-list mailing list