程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

If you dont learn decorators, you cant say you know Python in an interview

編輯:Python

picture
picture
Decorator
Python The decorator is one of the questions often asked in an interview , If your resume describes Python. Then 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()


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved