Potentially useful code snippets
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.4 KiB

from random import randint
'''
How a decorator works:
1. Create the decorator function. This is what @whatever is. It takes a function as input. It *can* also take parameters as per:
https://www.geeksforgeeks.org/decorators-with-parameters-in-python/
2. Inside that function is a wrapper function. It will take the same number of parameters as the decorated function.
3. Anything inside the wrapper function is defined, not run.
4. The function call with parameters passed through is called. Then the wrapped function is returned.
'''
#this is the decorator
def decor(func): #takes a function as an argument
def x(z): # z = arguments passed from function that was decorated. Note that the number of arguments must be the same.
''' Decorator function wrapper must take the same number of arguments or it will fail
'''
print('now with decoration') #extra shit from the decorator
func(z) #run that function WHEN CALLED ON. Not now, because it is inside a function definition.
return x #return the decorator function
@decor #invoke the decorator
def z(number):
print(number)
z(3)
#this is the functional equivalent
def decor2(func):
def x(z):
print('also with decoration')
func(z)
return x
def q(number):
print(number)
zz=decor2(q)
zz(3)
##another example
@decor
def othershite(thing):
x=randint(1,100)
print(f'here is some other shite and a random number({x}) plus {thing}')
othershite('piztak')