current position:Home>Python 3 development function
Python 3 development function
2022-05-15 02:32:50【Dream of looking for flowers~~】
1. General parameter def ada(x,y) def add (×=4,y=5)
It can receive both location parameters and keyword parameters .
2. Variable position tube parameters def total (*args)
args Will collect 0 One or any arguments , Collect into an immutable tuple *args * Modified formal parameters represent variable parameters , It can provide if the next remainder
The argument of your pass parameter by bit , Will be collected into meta groups by formal parameters , Tuples are immutable
*args be called Variable position parameter
Variable parameters can already be used 0 An argument , So you don't need a default value
3. Variable keyword parameters def fn (**kwargs) keyword arguments
** It's a modifier , Modify the following identifier , Used to kwargs
Only the remaining keyword arguments can be collected
The identifier can be composed of letters 、 Numbers 、 Just make it up , But it can't start with a number
4.keyword only Keyword parameters only
*args, Then the non deformable parameter
*, The identifiers that appear are generally keyword-only. except **kwargs
5. positional-only Only positional parameters 3.8+
At present, it is seldom used , Only individual function declarations use
Argument transmission :
(1) According to the position
(2) keyword
It can be mixed , The location parameter must be passed before the keyword parameter
Parameter deconstruction can only be used in the bracket when the function is called .
Untie into Pass parameters by location
When providing arguments to functions , You can use... Before an iteratable object * perhaps ** To deconstruct the structure , Extract all the elements as the arguments of the function
Use * Solution composition position transmission parameter
Use ** The solution forms a keyword to pass parameters
The number of extracted elements should match the requirements of parameters
Local, Local scope 、 Local scope local Namespace . Function call , End of call
Enclosing,Python2.2 Introduced nested functions , Implemented closure , This is the namespace of the external function of the nested function
Global, Global scope , That is, the namespace of a module . The module is import Created on , The interpreter dies when it exits
Build-in, The namespace of the built-in module , The life cycle starts with Python Created when the interpreter starts to die when the interpreter exits . for example print(open),print and open Are built-in variables
So the search order of a noun is LEGB
Decorator
Call of single argument function + assignment
import time
import datetime
def logger(fn):
def wrapper(*args, **kwargs):
print(' Pre call enhancement ')
start = datetime.datetime.now()
ret = fn(*args, **kwargs) # Parameters of deconstruction
print(' Post call enhancement ')
delta = (datetime.datetime.now() - start).total_seconds()
print('Function {} took {}s.'.format(fn.__name__, delta))
return ret
return wrapper
@logger
def add(x, y):
time.sleep(3)
return x + y
print(add(100, 200))
-----------------------------------------------------------------
def logger(fn): # fn Namely add, logger Equivalent to a unique parameter
def wrapper(*args, **kwargs): # wrapped(4,5) args=(4,5) {}
print('add 4 5')
print(' Call the... Executed before , enhance ')
ret = fn(*args, **kwargs) # Closure old add(4, 5) ——》9
print(' Executed after the call , enhance ')
return ret
return wrapper
@logger #logger It's decorator grammar , Decorate the identifier below add = logger(add)
# It brings up the following function identifier or identifier as logger The only argument to
def add(x, y):
return x + y
result = add(4, 5)
print(result)
###
@logger Decorator syntax , The function is to change the name of the function or class decorated below / The identifier is proposed as logger The only argument to the expression logger(add),
logger Function call , return wrapper,add amount to wrapper( Point to warpper The function object pointed to )
After calling, it will be assigned to add, therefore add The identifier is no longer the original add, Has been transformed into warpper( The function object defined above ) 了 , Calling logger It's the time to have ,logger(add),add(x, y) That's what it's all about wrapper The ginseng ,fn The closure is preserved ( The original add)
logger The one that doesn't write anything at the back is called a nonparametric decorator , A parameterless decorator is equivalent to a single parameter function , Above fn You can write a parameter later ( Parameters do not need to be coriolised , The default value is ) in order to @logger # Equivalent to add=wrapper <=>add = logger(add), So in (fn) Looks like a one parameter function , We must get a single parameter function , and logger As a decorator, grammar can be written here ,logger(add) Will take the extraction below as a “ Single argument ”
copyright notice
author[Dream of looking for flowers~~],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/132/202205120520121753.html
The sidebar is recommended
- 【python】UI/ function code seperated(ISP), TCP server receive multi client and send to a client
- Python introduction notes-1 syntax rules
- Python getting started notes - 3 common built-in functions in Python
- Python -- K-means clustering algorithm
- Python getting started notes - 4 Python operators
- Windows Python 3 installation & environment variable configuration
- Difference between Python multithreading start () and run () methods (turn)
- Install the corresponding packages for multiple versions of Python
- Python finds the corresponding substance according to the conditions and records it
- Python application scenarios and market demand
guess what you like
Python experience lesson Chapter 1 01print function
Python experience lesson Chapter 1 02 data types
Python experience lesson Chapter 1 03 conditional judgment
Python code writing specification and basic usage
Summary of Python file reading and writing methods for data analysis (open | CSV | dataframe | openpyxl)
Python data calculation method for data analysis part I (math|numpy)
Accelerating parallel computing based on python (BL) 136
[Python @ Little Turtle online class] P8 string (1) slicing & palindromes & changing the case of string & aligning the left, middle and right of string
[Python @ Little Turtle online class] P8 string (3) judgment
[Python @ Little Turtle online course] P8 string (2) find and replace
Random recommended
- Common modules and third-party libraries of Python notes in class
- Educoder Linux and Python Programming 2021 (basic syntax of classes) - level 2: properties and instantiation of classes
- Educoder Linux and Python Programming 2021 (basic syntax of classes) - level 1: Declaration and definition of classes
- Educoder Linux and Python Programming 2021 (basic syntax of classes) - Level 3: binding and method calling
- Educoder Linux and Python Programming 2021 (basic syntax of classes) - level 4: static methods and class methods
- Educoder Linux and Python Programming 2021 (basic syntax of classes) - level 5: class import
- Python: unable to connect because the target computer actively refused
- If I can only choose one of the python introductory books on the market for you, I will choose this one
- Python simulation | how to manipulate the winning or losing of football matches
- How to learn after joining our Python zero foundation learning group?
- Why choose Python as a programming language
- Functions in Python
- Python version of the lone brave | drawing + playing + Music Visualization
- Smplify -python2. seven
- Python office automation: use Python to automatically insert signatures into docx files
- Python uses the opencv method to automatically insert the signed image into any position of the image
- Python automatically inserts signatures into PDF files (pypdf2)
- Basic learning notes of Python
- Numpy, pandas, Matplotlib learning
- [brush question Python] the problem of cutting and selling pipes to maximize profits
- [Python] gradient descent method to solve the trough of univariate quadratic function
- Python regular expression
- [Python GUI] wxPython automated data generator practice
- Python script compilation process
- [Python faiss library] (I) Introduction
- Python moves (copies) the pictures (files) under one file to another folder
- Python crawling 51job position information (regular violence matching)
- Python Post Bar irrigation script
- Python simulation QR code login Baidu
- Python calls wechat to send message call through COM port
- Analysis of birthday paradox in Python
- Equal scale compression of image files in Python
- Python dynamic programming (knapsack problem and longest common substring)
- Introduction to Python Programming and data analysis (I) basic use of built-in functions
- Introduction to Python Programming and data analysis (II) basic use of list derivation
- Introduction to Python Programming and data analysis (III) basic use of branch and process control
- Python turtle painting Chinese characters
- [a quick introduction and comparison of multiple languages -- JavaScript, typescript, python, golang, trust, Java, ruby]
- Relevant knowledge of Python web development (I)
- python3. Understanding of ID function in 6