472,791 Members | 1,641 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,791 software developers and data experts.

Calling every method of an object from __init__

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

Jun 19 '06 #1
6 1858
> 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


Jun 19 '06 #2
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

iD8DBQFElwaQrgn0plK5qqURAoYMAJ41MX9UPa3Z7fzB9OLTyA fOnYf3HACfeMIU
5f6EIPWjVXzhsJbCXdMMXcs=
=Tsd9
-----END PGP SIGNATURE-----

Jun 19 '06 #3
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

Jun 19 '06 #4
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.variablenumberofargsohbuggerbacktothedrawingbo ard 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
Jun 19 '06 #5
Ten
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.
Jun 20 '06 #6
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 'o****@xiludom.gro'.split('@')])"
Jun 20 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Martin Maney | last post by:
I've been to the cookbook (both forms, since they're sometimes usefully different), but that gave rise to more questions than answers. Heck, let me pull some of them up while I'm at it. ...
6
by: Steven Bethard | last post by:
So when I'm writing a class and I define an __init__ method, I sometimes haven't called object.__init__, e.g.: class C(object): def __init__(self, x): self.x = x instead of class...
3
by: Christian Dieterich | last post by:
Hi, I need to create many instances of a class D that inherits from a class B. Since the constructor of B is expensive I'd like to execute it only if it's really unavoidable. Below is an example...
14
by: Axel Straschil | last post by:
Hello! Im working with new (object) classes and normaly call init of ther motherclass with callin super(...), workes fine. No, I've got a case with multiple inherance and want to ask if this...
2
by: Andrea Gavana | last post by:
Hello NG, this may seem a stupid (or even impossible) question, but my knowlegde of Python is quite limited. I have basically a simple graphical user interface that contains a Panel, another...
10
by: Finger.Octopus | last post by:
Hello, I have been trying to call the super constructor from my derived class but its not working as expected. See the code: class HTMLMain: def __init__(self): self.text = "<HTML><BODY>";...
3
by: Steven D'Aprano | last post by:
I have a class that has a distinct "empty" state. In the empty state, it shouldn't have any data attributes, but it should still have methods. The analogy is with a list: an empty list still has...
1
by: Maese Fernando | last post by:
Hi, I'm getting an odd error while trying to call the __init__ method of a super class: BaseField.__init__(self) TypeError: unbound method __init__() must be called with BaseField instance...
1
by: Ryan Krauss | last post by:
I am trying to call a parent's __init__ method from the child's: class ArbitraryBlock(InnerBlock): def __init__(self, codelist, noout=False, **kwargs): InnerBlock.__init__(self, codelist,...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: lllomh | last post by:
How does React native implement an English player?
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.