I am a new hand for Python. When I learning decorator and class. There are something I totally dont understand
when we take a look an decorator example:
class Log_dec(object):
def __init__(self, func):
self.func = func
def __call__(self, args):
print('do something before function')
Result=self.func(args)
print(Result)
print('do something after function')
@Log_dec
def myFunc(name):
return 'My Name is %s'%name
myFunc('Haha')
Result is:
do something before function
My Name is Haha
do something after function
If we compare to another example:
class Log_dec(object):
def __init__(self, func):
self.func = func
def __call__(self, args):
print('do something before function')
Result=self.func(args)
print(Result)
print('do something after function')
def __CallTwice__(self,a_default_variable):
print('do something different')
Result_2=self.func(a_default_variable)
print(Result_2)
@Log_dec
def myFunc(name):
return 'My Name is %s'%name
myFunc('Haha')
Resuls is still:
do something before function
My Name is Haha
do something after function
It seems when we execute myFunc('Haha')
, the function myFunc
goes into func
in the __init__
and the string Haha
goes into args
in the __call__
.
My questions is, why the string Haha
dont goes into a_defult_variable
in the __CallTwice__
??? That makes me confusced.
Or let's say, Why the function myFunc
don't goes into a_default_variable
in the __CallTwice__
. Because I think apparently def __init__(self, func):
has a same format as def __CallTwice__(self,a_default_variable):
Does it?