Python The decorator is one of the questions often asked in an interview , If your resume describes Python, So the probability will be asked, so how should we answer this question ? Here I will explain the function of the decorator from several angles , You can choose what suits you
1.python Basic principle of decorator
Python Decorator in , It's essentially a higher-order function , Here, the higher-order function is specified as " A return value is a function of the function "
2. The syntax of the decorator
stay python We use decorators in our daily life , There are two components
@ Symbol call decorator
Define the method of being decorated
Here's an example :
@ Decorator name
Decorated function
@logger
def func():
pass
3. What do you usually do ?
Decorators can be used without modifying functions , Add extra features . This is the official definition of decorator
In fact, we will put some other than business functions , Accessory requirements are realized by decorators . such as : Add logging for our function , Performance monitor , Buried point counter . You know that , Modifying a written function is a very troublesome and error prone thing . So it's suitable for “ Without modifying the internal code of the function , Pack it with some extra features ” That is, the decorator
4. Common decorators
staticmethod Used to modify the methods in the class , So that the method can directly access , Such as cls.foo().
classmethod and staticmehod similar , The difference lies in staticmethod,classmethod Will class Into the modified method
class A(object):
a = 1
def __init__(self):
self.a = 2
@staticmethod
def foo1():
print A.a
@classmethod
def foo2(cls):
print "class a is", cls.a
print "instance a is", cls().a
property The access and assignment of attributes can be realized by functions , Thus, some functions such as parameter checking can be added to the function , At the same time, the way of access and assignment does not change when used externally .
Note that the method names of access and assignment are the same
class A(object):
def __init__(self):
self.__count = 0
@property
def count(self):
return self.__count
@count.setter
def count(self, value):
if not isinstance(value, int):
raise ValueError('count must be an integer!')
self.__count = value
a = A()
print a.count
a.count = 1
print a.count
a.count = "a" # raise ValueError
functools.wraps Used in decorator code . You can put the of the original function name Wait for attributes to be copied to wrapper() Function , In this way, we can get the real function name attribute , instead of wrapper
import functools
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print '%s %s():' % (text, func.__name__)
return func(*args, **kw)
return wrapper
return decorator
5. How to write a decorator
#!/anaconda3/envs/FEALPy/bin python3.7
# -*- coding: utf-8 -*-
# ---
# @File: Decorator syntax .py
# @Author: Bull
# ---
# Define decorator functions
# 1. Examples of simple decorators
def logger(func):# stay python in , Everything is an object
def wrapper(*args,**kw):
print(" Enter the decorator function ")
func(*args,**kw)# The real function is called again in the decorator
func(*args, **kw)
print(" The function of the decorator is completed ")
return wrapper
@logger#=logger(add)
def add(x,y):
print(' Enter the modified function ')
print(f'{x}+{y}={x+y}')
# add(1,2)
# 2. Parameter decorator
def say_hello(contry):
def wrapper(func):
def second(*args,**kw):
if contry == 'china':
print(" From decorator ‘ Hello ’")
elif contry == 'america':
print(' From decorator "hello"')
else:
return
func(*args,**kw)
return second
return wrapper
@say_hello('america')
def american():
print("I am from America")
@say_hello('china')
def china():
print(' I'm from China. ')
american()
print('*'*30)
china()
The technology industry should continue to learn , Don't fight alone in your study , It's best to keep warm , Achieve each other and grow together , The effect of mass effect is very powerful , Let's learn together , Punch in together , Will be more motivated to learn , And you can stick to it . You can join our testing technology exchange group :914172719( There are various software testing resources and technical discussions )
Here's a message for you , Mutual encouragement : When our abilities are insufficient , The first thing to do is internal practice ! When we are strong enough , You can look outside !
Finally, we also prepared a supporting learning resource for you , You can scan the QR code below via wechat , Get one for free 216 Page software testing engineer interview guide document information . And the corresponding video learning tutorial is free to share !, The information includes basic knowledge 、Linux necessary 、Shell、 The principles of the Internet 、Mysql database 、 Special topic of bag capturing tools 、 Interface testing tool 、 Test advanced -Python Programming 、Web automated testing 、APP automated testing 、 Interface automation testing 、 Testing advanced continuous integration 、 Test architecture development test framework 、 Performance testing 、 Safety test, etc. .
Friends who like software testing , If my blog helps you 、 If you like my blog content , please “ give the thumbs-up ” “ Comment on ” “ Collection ” One button, three links !
Why is the test post a giant pit ?10 The tester told you not to be fooled
Interview must ask Linux The order will help you tidy up …
The man who leaves work on time , Promoted before me …
Bubble share price 、 Delivery boy is going to lose his job ? Whether the tester will join the meituan ? One article will show you the truth behind it
In outsourcing ! There was a trough 5 Years of time makes my annual salary close to 100W… I don't give up , Let me see the most beautiful tomorrow …
Two ordinary books , I've been to Alibaba , Up to now, annual salary 40W+ Senior Test Engineer , My two-year career change experience …