Lets see how python function work,
Code 1:
def myfunc(a):Output 1:
print(a)
decorator = myfunc
decorator('It\'s Works')
It's Works
Code 2:
def myfunc(*args):Output 2:
print(args)
decorator = myfunc
decorator('It\'s', 'Works', 'Yeah', 'Must be ok')
("It's", 'Works', 'Yeah', 'Must be ok')
Code 3:
def myfunc(**kwargs):Output 3:
print(kwargs)
decorator = myfunc
decorator(a=1, b=2, c=3)
{'a':1, 'b':2, 'c':3}
Inner Function
Inner function is function inside function or we can call it nested function. Look at code bellow:
def myfunc(a):Output should be:
def inner_myfunc():
print(a)
return a
decorator = myfunc
decorator('inner myfunc')
'inner myfunc'from the code we can se that, argument or parameter a is accessible from inner function.
I have some question why I always wrote decorator = myfunc? I just want to show python function can be assigned to var as alias or pointer.
@some_decorator
def myfunc():
return a
it's mean:
myfunc = some_decorator(myfunc)
Lets try to the real code with decorator implementation:
# define logger function
# we will this for as decorator
def logger(func):
def inner(*args, **kwargs): #1
print "Arguments were: %s, %s" % (args, kwargs)
return func(*args, **kwargs) #2
return inner
# use the decorator
@logger
def myfunc1(x, y=1):
return x * y
# use the decorator
@logger
def myfunc2():
return 2
After define function now try to call myfunc1 and myfunc2:
# call function
myfunc1(5, 4)
# output should be
Arguments were: (5, 4), {}
20
# call function
myfunc1(1)
# output should be
Arguments were: (1,), {}
1
# call function
myfunc2()
# output should be
Arguments were: (), {}
2
If you need more explanation you can comment this post, just comment and I will try to answer :-).
Let Sleep.....
No comments:
Post a Comment