# A Sample class with init methodclassPerson:# init method or constructordef__init__(self,name):self.name=name# Sample Methoddefsay_hi(self):print('Hello, my name is',self.name)p=Person('Nikhil')p.say_hi()
output
Text Only
12
PS D:\work\python_work\ModernPython\codes\__init__\class_init\01> py.exe .\testprj.py
Hello, my name is Nikhil
classExample:def__init__(self):print("Instance Created")# Defining __call__ method def__call__(self):print("Instance is called via special method")# Instance created e=Example()# __call__ method will be called e()
output
Text Only
123
PS D:\work\python_work\ModernPython\codes\__call__\01> py.exe .\testprj.py
Instance Created
Instance is called via special method
classProduct:def__init__(self):print("Instance Created")# Defining __call__ method def__call__(self,a,b):print(a*b)# Instance created ans=Product()# __call__ method will be called ans(10,20)
output
Text Only
123
PS D:\work\python_work\ModernPython\codes\__call__\02> py.exe .\testprj.py
Instance Created
200
x="hello"ifnottype(x)isint:raiseTypeError("Only integers are allowed")
output
Text Only
12345
PS D:\work\python_work\ModernPython\codes\raise\02> py.exe .\testprj.py
Traceback (most recent call last):
File "D:\work\python_work\ModernPython\codes\raise\02\testprj.py", line 4, in <module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed
defhi(name="yasoob"):print("now you are inside the hi() function")defgreet():return"now you are in the greet() function"defwelcome():return"now you are in the welcome() function"print(greet())print(welcome())print("now you are back in the hi() function")hi()#output:now you are inside the hi() function# now you are in the greet() function# now you are in the welcome() function# now you are back in the hi() function# 上面展示了无论何时你调用hi(), greet()和welcome()将会同时被调用。# 然后greet()和welcome()函数在hi()函数之外是不能访问的,比如:greet()#outputs: NameError: name 'greet' is not defined
output
Text Only
1 2 3 4 5 6 7 8 910
PS D:\work\python_work\ModernPython\codes\decorators\decorator\02> py.exe .\testprj.py
now you are inside the hi() function
now you are in the greet() function
now you are in the welcome() function
now you are back in the hi() function
Traceback (most recent call last):
File "D:\work\python_work\ModernPython\codes\decorators\decorator\02\testprj.py", line 24, in <module>
greet()
^^^^^
NameError: name 'greet' is not defined
defhi(name="yasoob"):defgreet():return"now you are in the greet() function"defwelcome():return"now you are in the welcome() function"ifname=="yasoob":returngreetelse:returnwelcomea=hi()print(a)#outputs: <function greet at 0x7f2143c01500>#上面清晰地展示了`a`现在指向到hi()函数中的greet()函数#现在试试这个print(a())#outputs: now you are in the greet() function
output
Text Only
123
PS D:\work\python_work\ModernPython\codes\decorators\decorator\03> py.exe .\testprj.py
<function hi.<locals>.greet at 0x0000019AED09DF80>
now you are in the greet() function
Example 4 Passing a function as a parameter to another function¶
Python
1 2 3 4 5 6 7 8 910
defhi():return"hi yasoob!"defdoSomethingBeforeHi(func):print("I am doing some boring work before executing hi()")print(func())doSomethingBeforeHi(hi)#outputs:I am doing some boring work before executing hi()# hi yasoob!
output
Text Only
123
PS D:\work\python_work\ModernPython\codes\decorators\decorator\04> py.exe .\testprj.py
I am doing some boring work before executing hi()
hi yasoob!
defa_new_decorator(a_func):defwrapTheFunction():print("I am doing some boring work before executing a_func()")a_func()print("I am doing some boring work after executing a_func()")returnwrapTheFunctiondefa_function_requiring_decoration():print("I am the function which needs some decoration to remove my foul smell")a_function_requiring_decoration()#outputs: "I am the function which needs some decoration to remove my foul smell"a_function_requiring_decoration=a_new_decorator(a_function_requiring_decoration)#now a_function_requiring_decoration is wrapped by wrapTheFunction()a_function_requiring_decoration()#outputs:I am doing some boring work before executing a_func()# I am the function which needs some decoration to remove my foul smell# I am doing some boring work after executing a_func()
output
Text Only
12345
PS D:\work\python_work\ModernPython\codes\decorators\decorator\05> py.exe .\testprj.py
I am the function which needs some decoration to remove my foul smell
I am doing some boring work before executing a_func()
I am the function which needs some decoration to remove my foul smell
I am doing some boring work after executing a_func()
defa_new_decorator(a_func):defwrapTheFunction():print("I am doing some boring work before executing a_func()")a_func()print("I am doing some boring work after executing a_func()")returnwrapTheFunction@a_new_decoratordefa_function_requiring_decoration():"""Hey you! Decorate me!"""print("I am the function which needs some decoration to ""remove my foul smell")a_function_requiring_decoration()#outputs: I am doing some boring work before executing a_func()# I am the function which needs some decoration to remove my foul smell# I am doing some boring work after executing a_func()#the @a_new_decorator is just a short way of saying:a_function_requiring_decoration=a_new_decorator(a_function_requiring_decoration)
output
Text Only
1234
PS D:\work\python_work\ModernPython\codes\decorators\decorator\06a> py.exe .\testprj.py
I am doing some boring work before executing a_func()
I am the function which needs some decoration to remove my foul smell
I am doing some boring work after executing a_func()
defa_new_decorator(a_func):defwrapTheFunction():print("I am doing some boring work before executing a_func()")a_func()print("I am doing some boring work after executing a_func()")returnwrapTheFunction@a_new_decoratordefa_function_requiring_decoration():"""Hey you! Decorate me!"""print("I am the function which needs some decoration to ""remove my foul smell")a_function_requiring_decoration()#outputs: I am doing some boring work before executing a_func()# I am the function which needs some decoration to remove my foul smell# I am doing some boring work after executing a_func()#the @a_new_decorator is just a short way of saying:a_function_requiring_decoration=a_new_decorator(a_function_requiring_decoration)print(a_function_requiring_decoration.__name__)# Output: wrapTheFunction
output
Text Only
12345
PS D:\work\python_work\ModernPython\codes\decorators\decorator\06b> py.exe .\testprj.py
I am doing some boring work before executing a_func()
I am the function which needs some decoration to remove my foul smell
I am doing some boring work after executing a_func()
wrapTheFunction
fromfunctoolsimportwrapsdefa_new_decorator(a_func):@wraps(a_func)defwrapTheFunction():print("I am doing some boring work before executing a_func()")a_func()print("I am doing some boring work after executing a_func()")returnwrapTheFunction@a_new_decoratordefa_function_requiring_decoration():"""Hey yo! Decorate me!"""print("I am the function which needs some decoration to ""remove my foul smell")a_function_requiring_decoration()print(a_function_requiring_decoration.__name__)# Output: a_function_requiring_decoration
output
Text Only
12345
PS D:\work\python_work\ModernPython\codes\decorators\decorator\07> py.exe .\testprj.py
I am doing some boring work before executing a_func()
I am the function which needs some decoration to remove my foul smell
I am doing some boring work after executing a_func()
a_function_requiring_decoration
fromfunctoolsimportwrapsdefdecorator_name(f):@wraps(f)defdecorated(*args,**kwargs):ifnotcan_run:return"Function will not run"returnf(*args,**kwargs)returndecorated@decorator_namedeffunc():return("Function is running")can_run=Trueprint(func())# Output: Function is runningcan_run=Falseprint(func())# Output: Function will not run
output
Text Only
123
PS D:\work\python_work\ModernPython\codes\decorators\decorator\08> py.exe .\testprj.py
Function is running
Function will not run
defdecorator_function(original_function):defwrapper_function(*args,**kwargs):print("Executed Before",original_function.__name__)result=original_function(*args,**kwargs)print("Executed After",original_function.__name__,"\n")returnresultreturnwrapper_function@decorator_functiondefdisplay_info(name,age):print("display_info ran with qiguments ({}, {})".format(name,age))display_info('john',25)
output
Text Only
1234
PS D:\work\python_work\ModernPython\codes\decorators\Arguments\01> py.exe .\testprj.py
Executed Before display_info
display_info ran with qiguments (john, 25)
Executed After display_info
defdecorator_function(original_function):defwrapper_function(*args,**kwargs):print("Executed Before",original_function.__name__)result=original_function(*args,**kwargs)print("Executed After",original_function.__name__,"\n")returnresultreturnwrapper_function@decorator_functiondefdisplay_info(name,age):print("display_info ran with qiguments ({}, {})".format(name,age))display_info('john',25)
output
Text Only
1234
PS D:\work\python_work\ModernPython\codes\decorators\Arguments\01> py.exe .\testprj.py
Executed Before display_info
display_info ran with qiguments (john, 25)
Executed After display_info
defdecorator_function(original_function):defwrapper_function(*args,**kwargs):print("Executed Before",original_function.__name__)result=original_function(*args,**kwargs)print("Executed After",original_function.__name__,"\n")returnresultreturnwrapper_function@decorator_functiondefdisplay_info(name,age):print("display_info ran with qiguments ({}, {})".format(name,age))display_info('john',25)display_info('Travis',30)
output
Text Only
12345678
PS D:\work\python_work\ModernPython\codes\decorators\Arguments\01a> py.exe .\testprj.py
Executed Before display_info
display_info ran with qiguments (john, 25)
Executed After display_info
Executed Before display_info
display_info ran with qiguments (Travis, 30)
Executed After display_info
defprefix_decorator(prefix):defdecorator_function(original_function):defwrapper_function(*args,**kwargs):print(prefix,"Executed Before",original_function.__name__)result=original_function(*args,**kwargs)print(prefix,"Executed After",original_function.__name__,"\n")returnresultreturnwrapper_functionreturndecorator_function@prefix_decorator('TESTING')defdisplay_info(name,age):print("display_info ran with qiguments ({}, {})".format(name,age))display_info('john',25)display_info('Travis',30)
output
Text Only
12345678
PS D:\work\python_work\ModernPython\codes\decorators\Arguments\01b> py.exe .\testprj.py
TESTING Executed Before display_info
display_info ran with qiguments (john, 25)
TESTING Executed After display_info
TESTING Executed Before display_info
display_info ran with qiguments (Travis, 30)
TESTING Executed After display_info
defprefix_decorator(prefix):defdecorator_function(original_function):defwrapper_function(*args,**kwargs):print(prefix,"Executed Before",original_function.__name__)result=original_function(*args,**kwargs)print(prefix,"Executed After",original_function.__name__,"\n")returnresultreturnwrapper_functionreturndecorator_function@prefix_decorator('TESTING')defdisplay_info(name,age):print("display_info ran with arguments ({}, {})".format(name,age))@prefix_decorator('DEBUG')defadd_abc(a,b,c):print("add_abc ran with arguments ({}+{}+{}={})".format(a,b,c,a+b+c))display_info('john',25)display_info('Travis',30)add_abc(1,2,3)add_abc(a=1,b=2,c=3)add_abc(a=3,b=2,c=1)
output
Text Only
1 2 3 4 5 6 7 8 91011121314151617181920
PS D:\work\python_work\ModernPython\codes\decorators\Arguments\01c> py.exe .\testprj.py
TESTING Executed Before display_info
display_info ran with arguments (john, 25)
TESTING Executed After display_info
TESTING Executed Before display_info
display_info ran with arguments (Travis, 30)
TESTING Executed After display_info
DEBUG Executed Before add_abc
add_abc ran with arguments (1+2+3=6)
DEBUG Executed After add_abc
DEBUG Executed Before add_abc
add_abc ran with arguments (1+2+3=6)
DEBUG Executed After add_abc
DEBUG Executed Before add_abc
add_abc ran with arguments (3+2+1=6)
DEBUG Executed After add_abc
fromfunctoolsimportwrapsdefhello_decorator(num):"""Simple decorator function that supports parameters"""definner_func(func):@wraps(func)defwrapper(*args,**kwargs):"""Simple decorator wrapper function"""result=func(*args,**kwargs)result=result+numreturnresultreturnwrapperreturninner_func@hello_decorator(100)defadd(a,b):"""Simple function that returns sum of two numbers"""returna+b@hello_decorator(200)defmultiply(a,b):"""Simple function that returns multiplication of two numbers"""returna*bif__name__=='__main__':output1=add(2,2)print('Result:: ',output1)print("="*25)output2=multiply(4,2)print('Result:: ',output2)