Python:为类的任何方法做些什么? [英] Python: Do something for any method of a class?

查看:141
本文介绍了Python:为类的任何方法做些什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Human():

)def eat():
print(eating)

def sleep():
print(sleeping)

def throne( ):
print(在宝座上)

然后我运行所有的方法

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

我想运行 print(I am )为每个被调用的方法。所以我应该得到像

 我是:

我是:
睡觉
我是:
的宝座

有没有办法做到这一点无需重新格式化每种方法?

解决方案

如果您无法更改如何调用方法,可以使用 __ getattribute __ 魔术方法(方法属性也记得!)你只需要小心地检查属性的类型,这样你就不会在每次你想要访问任何sting或int属性时打印我是:你可能会有:

 导入类型

类人类(对象):
def __getattribute __(self ,attr):
method = object .__ getattribute __(self,attr)
如果不是方法:
抛出异常(方法%s未实现%attr)
if方法)== types.MethodType:
print我是:
返回方法

def eat(self):
printeating

def sleep(self):
printsleeping

def throne(self):
printon the throne

John = Human()
John.eat()
John.sleep()
John.thro ne()

输出:

<$ p $我是:

我是:
睡觉
我是:
在宝座上


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?

解决方案

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 sting or int attributes you may have:

import types

class Human(object):
    def __getattribute__(self, attr):
        method = object.__getattribute__(self, attr)
        if not method:
            raise Exception("Method %s not implemented" % attr)
        if type(method) == types.MethodType:
             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

这篇关于Python:为类的任何方法做些什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆