Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

basic question for python decorator mechanism

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?

like image 251
lululu Avatar asked Sep 25 '26 19:09

lululu


1 Answers

This answer just rewrites your example with self-documenting names and without the @-syntax.

def create_new_function_from_existing_function(old_function): # def log
    def new_function(*some_positional_arguments, **some_keyword_arguments): # define wrapped function
        print('call %s:' % old_function.__name__)
        return old_function(*some_positional_arguments, **some_keyword_arguments)
    return new_function # return wrapped function

def now(x, y):
    print('2021-9-3 value=', x + y)

now = create_new_function_from_existing_function(now) # @log ...
like image 169
timgeb Avatar answered Sep 28 '26 08:09

timgeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!