Calling every method of an object from __init__

Discussion in 'Python' started by Rob Cowie, Jun 19, 2006.

  1. Rob Cowie

    Rob Cowie Guest

    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'

    Thanks,

    Rob C
     
    Rob Cowie, Jun 19, 2006
    #1
    1. Advertising

  2. Rob Cowie

    K.S.Sreeram Guest

    Rob Cowie wrote:
    > 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 k in dir(self) :
    if not k.startswith('__') :
    v = getattr( self, k )
    v()
    def test(self):
    print 'The test method'
    def hello(self):
    print 'Hello user'


    you can also add a test for 'if callable(v) :' to the for loop if you
    have data fields in Foo.

    Regards
    Sreeram


    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.4.2.2 (MingW32)
    Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

    iD8DBQFElwaQrgn0plK5qqURAoYMAJ41MX9UPa3Z7fzB9OLTyAfOnYf3HACfeMIU
    5f6EIPWjVXzhsJbCXdMMXcs=
    =Tsd9
    -----END PGP SIGNATURE-----
     
    K.S.Sreeram, Jun 19, 2006
    #2
    1. Advertising

  3. Rob Cowie

    Tim Chase Guest

    > 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
     
    Tim Chase, Jun 19, 2006
    #3
  4. 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'
    >
    > Thanks,
    >
    > Rob C



    First off, calling *every* method of an object is most likely a bad
    idea. A class has special methods defined automatically and you
    probably don't intend calling those. The way to go is have a naming
    convention for the methods you want to call, e.g. methods starting with
    "dump_". In this case you could use the inspect module to pick the
    object's methods and filter out the irrelevant methods:

    import inspect

    class Foo(object):
    def __init__(self):
    for name,method in inspect.getmembers(self,inspect.ismethod):
    if name.startswith('dump_'):
    method()
    def dump_f(self):
    print 'The test method'
    def dump_g(self):
    print 'Hello user'

    if __name__ == '__main__':
    Foo()


    George
     
    George Sakkis, Jun 19, 2006
    #4
  5. Rob Cowie

    John Machin Guest

    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
     
    John Machin, Jun 19, 2006
    #5
  6. Rob Cowie

    Ten Guest

    On Monday 19 June 2006 20:55, 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'
    >
    > Thanks,
    >
    > Rob C


    May I ask what the intended application is?

    Calling *everything* callable in an instance is pretty much guaranteed to cause a problem,
    and a reusable external function might be better in any case.

    The code posted kinda-sorta implies that you're looking to call only *your created* methods,
    is that what you mean?

    If so, you probably need to bite the bullet and stick to a naming convention
    which excludes __class__, __init__, __call__ and so on, ie: no leading underscores a la public
    methods, as well as making sure your methods actually support being called with no args.

    Assuming all that, let me be the first in this thread to pointlessly use a list comprehension:


    class bork(object):
    def __init__(self):
    #in __init__ method as requested...
    [self.__getattribute__(i)() for i in dir(self) if not i.startswith('__') and callable(self.__getattribute__(i))]
    def hello(self):
    print 'hello'
    def testyflops(self):
    print 'breasts'

    x=bork()
    hello
    breasts

    or, nicer, you could have:

    def callall(x):
    [x.__getattribute__(i)() for i in dir(x) if not i.startswith('__') and callable(x.__getattribute__(i))]

    then use:

    class bink(object):
    def __init__(self):
    callall(self)
    def hatstand(self):
    print 'Argh!'
    def jackbenimble(self):
    print 'Freud!'

    y=bink()
    Argh!
    Freud!

    as well as being able to

    callall(anInstanceOfSomeOtherClass)

    ....with other objects if you're just so wild and rebellious that you don't care about errors, and laugh in the face of
    arguments. :)

    HTH,

    Ten

    PS: Just out of curiosity, would you mind saying what this is for?


    --
    There are 10 types of people in this world,
    those who understand binary, and those who don't.
     
    Ten, Jun 20, 2006
    #6
  7. Tim Chase wrote:
    (snip)

    >>>> class Foo(object):

    > ... def __init__(self):
    > ... for method in dir(self):
    > ... if method == method.strip("_"):

    if not method.startswith('_'):

    --
    bruno desthuilliers
    python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
    p in ''.split('@')])"
     
    bruno at modulix, Jun 20, 2006
    #7
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Steven Bethard
    Replies:
    2
    Views:
    458
    Steven Bethard
    Feb 16, 2005
  2. Kent Johnson
    Replies:
    7
    Views:
    915
    Jan Niklas Fingerle
    Feb 12, 2006
  3. Maese Fernando
    Replies:
    1
    Views:
    269
    Peter Otten
    May 18, 2008
  4. Ryan Krauss

    problem calling parent's __init__ method

    Ryan Krauss, Aug 7, 2008, in forum: Python
    Replies:
    2
    Views:
    509
    Ryan Krauss
    Aug 7, 2008
  5. Ramchandra Apte
    Replies:
    17
    Views:
    342
    Manuel Pégourié-Gonnard
    Sep 30, 2012
Loading...

Share This Page