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

2024-10-06 12:45:57 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个有很多方法的类:

class Human():

  def eat():
    print("eating")

  def sleep():
    print("sleeping")

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

然后我用

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

我想为每个被调用的方法运行print("I am")。所以我应该买些

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

有没有一种方法可以做到这一点而不必重新格式化每个方法?


Tags: the方法ondefsleepamjohnclass