Python:为类的任何方法做些什么?

Pit*_*kos 13 python methods function

假设我有一个包含大量方法的类:

class Human():

  def eat():
    print("eating")

  def sleep():
    print("sleeping")

  def throne():
    print("on the throne")
Run Code Online (Sandbox Code Playgroud)

然后我运行所有的方法

John=Human()
John.eat()
John.sleep()
John.throne()
Run Code Online (Sandbox Code Playgroud)

我想print("I am")为每个被调用的方法运行.所以我应该得到类似的东西

I am:
eating
I am:
sleeping
I am:
on the throne
Run Code Online (Sandbox Code Playgroud)

有没有办法在不重新格式化每种方法的情况下执行此操作?

net*_*tux 14

如果你无法改变调用方法的方法,你可以使用__getattribute__魔法(方法属性也记得!)你只需要小心检查属性的类型,这样你就不会每次都打印"我是:"您想要访问您可能拥有的任何字符串或int属性:

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()
Run Code Online (Sandbox Code Playgroud)

输出:

I am:
eating
I am:
sleeping
I am:
on the throne
Run Code Online (Sandbox Code Playgroud)

  • 例如,当属性是修补到实例上的函数时,例如“my_instance.foo = lambda: 123”,就会出现此实现的问题。我通常更喜欢使用内置的“callable”进行检查。 (2认同)