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.