python输出自己的名字,Python - 每当调用类的方法时打印方法名称

I need to perform certain operations everytime the methods of a particular class is called (for example log the method name). How can this be achieved in Python in a generic way?

解决方案

Decorate callable attributes from within a metaclass:

from functools import wraps

def _log_method(val):

@wraps(val)

def wrapper(*a, **ka):

print(val.__name__, 'is called')

val(*a, **ka)

return wrapper

class LogMethodCalls(type):

def __new__(cls, cls_name, bases, attrs):

for name, attr in attrs.items():

if callable(attr):

attrs[name] = _log_method(attr)

return type.__new__(cls, cls_name, bases, attrs)

class Foo(metaclass=LogMethodCalls):

def my_method(self):

pass

Foo().my_method() # my_method is called

Warning: This code only works for instance methods, methods that were decorated with @classmethod or @staticmethod will not be logged (because classmethod and staticmethod objects are not callable - they're just non-data descriptors).

The following works for class methods and static methods as well:

from functools import wraps

def _log_method(val):

@wraps(val)

def wrapper(*a, **ka):

print('calling', val.__name__)

val(*a, **ka)

return wrapper

class LogMethodCalls(type):

def __new__(cls, cls_name, bases, attrs):

for name, attr in attrs.items():

if callable(attr):

attrs[name] = _log_method(attr)

elif isinstance(attr, (classmethod, staticmethod)):

attrs[name] = type(attr)(_log_method(attr.__func__))

return type.__new__(cls, cls_name, bases, attrs)

class Foo(metaclass=LogMethodCalls):

def my_instance_method(self):

pass

@classmethod

def my_class_method(cls):

pass

@staticmethod

def my_static_method():

pass

Foo().my_instance_method() # calling my_instance_method

Foo.my_class_method() # calling my_class_method

Foo.my_static_method() # calling my_static_method

They have __func__ attributes that we can decorate.

Note that you'll need to use

class Foo(object):

__metaclass__ = LogMethodCalls

in Python 2.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值