I am using Python 3.5 and i try to print the number of function-calls with python-decorator. So here is my example:
import inspect
def logWrapper(func):
def wrapper_func(self, *args, **kwargs):
wrapper_func.calls += 1
self.logger.info('Func: {}' .format(func.__name__) )
return func(self, *args, **kwargs)
wrapper_func.calls=0
return wrapper_func
class A:
__init__(self):
print('created')
@logWrapper
def myfunction1(self, var1):
print('var1: {}' .format(var1))
@logWrapper
def myfunction2(self, var2):
print('var2: {}' .format(var2))
if __name__ == "__main__":
Pal1=A()
Pal1.myfunction1('1')
Pal1.myfunction1('2')
Pal1.myfunction1('3')
Pal1.myfunction2('A')
function_list=inspect.getmembers(Pal1, predicate=inspect.ismethod)
for func in function_list:
method_to_call = getattr(A, func[0])
print( 'Function: {}; Calls: {}' .format(func[0], method_to_call.calls))
When i call Pal1.myfunction1.calls
and Pal1.myfunction2.calls
i got my correct results 3 and 1. But now i like to iterate throw every function of class A . When i try Pal1.func[0].calls
i got the error-message *** AttributeError: 'A' object has no attribute 'func'
, i also tried A.method_to_call.calls
and got the same results.
What i am doing wrong?
The problem is that you are calling instance methods as class methods.
For example, you cannot call
A.myfunction1('3')
However you can call,
inst = A()
inst.myfunction1('3')
When this is translated into the getattr
syntax, your code becomes
method_to_call = getattr(Pal1, func[0])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.