Python:为类的任何方法做些什么?
假设我有一个包含一系列方法的类:Python:为类的任何方法做些什么?,python,function,methods,Python,Function,Methods,假设我有一个包含一系列方法的类: 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: eating
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:
eating
I am:
sleeping
I am:
on the throne
有没有一种方法可以做到这一点,而不必重新格式化每个方法 如果您不介意将
\uuuuu init\uuuuuu
和\uuuu调用方法添加到类中,并将self
添加到方法的参数中,则可以执行此操作
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")
编辑:查看我的其他答案以获得更好的解决方案如果您无法更改调用方法的方式,您可以使用\uuuu getattribute\uuuuu
魔术方法(方法也是属性,请记住!)您只需小心检查属性的类型,以免打印“我是”:每次要访问任何字符串或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()
产出:
I am:
eating
I am:
sleeping
I am:
on the throne
如果您还想拥有参数,可以尝试使用元编程来更改类方法本身,以运行预/后操作,如的答案使用装饰器,将其应用于所有方法:如果您试图最小化需要进行的编辑数量,最简单的方法就是更改每个方法的定义。如果您正在寻找一种将更改隔离到单个位置的方法,以适用于任何当前或未来的方法,那么装饰器就是一种选择。为什么不使用函数def do(self,action)
,那么eat
就变成了self.do(“eating”)
而对输出的任何进一步更改都发生在一个地方。@jornsharpe实际上我就是这样做的。这似乎是最简单的方法。我试图用装饰器解决它,但它开始看起来像个怪物,所以放弃了。@Pithikos请参阅我的另一个解决方案,该解决方案不需要您更改调用方法的方式。此实现出现问题,例如,当属性是修补到实例上的函数时,例如,my_instance.foo=lambda:123
。我通常更喜欢使用内置的callable
进行检查。@BerislavLopac很好!更新了答案,改为使用callable