Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Do something for any method of a class?

Say I have a class with a bunch of methods:

class Human():

  def eat():
    print("eating")

  def sleep():
    print("sleeping")

  def throne():
    print("on the throne")

Then I run all the methods with

John=Human()
John.eat()
John.sleep()
John.throne()

I want to run print("I am") for each method being called. So I should get something like

I am:
eating
I am:
sleeping
I am:
on the throne

Is there a way to do this without having to reformat each method?

like image 366
Pithikos Avatar asked Sep 25 '14 11:09

Pithikos


1 Answers

You can do this if you don't mind adding an __init__ and __call__ method to your class and self to your method's arguments.

class Human():
    def __init__(self):
        return None
    def __call__(self, act):
        print "I am:"
        method = getattr(self, act)
        if not method:
            raise Exception("Method %s not implemented" % method_name)
        method()

    def eat(self):
        print "eating"

    def sleep(self):
        print "sleeping"

    def throne(self):
        print "on the throne"

John = Human()
John("eat")
John("sleep")
John("throne")

EDIT: see my other answer for a better solution

like image 150
nettux Avatar answered Nov 19 '22 00:11

nettux