Python: Do something for any method of a class?

前端 未结 3 1204
自闭症患者
自闭症患者 2021-02-19 03:01

Say I have a class with a bunch of methods:

class Human():

  def eat():
    print(\"eating\")

  def sleep():
    print(\"sleeping\")

  def throne():
    print         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-19 03:19

    If you can't change how you call your methods you can use the __getattribute__ magic method (methods are attributes too remember!) you just have to be careful to check the type of attributes so you don't print "I am:" every time you want to access any string or int attributes you may have:

    class Human(object):
        def __getattribute__(self, attr):
            method = object.__getattribute__(self, attr)
            if not method:
                raise Exception("Method %s not implemented" % attr)
            if callable(method):
                 print "I am:"
            return 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()
    

    Outputs:

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

提交回复
热议问题