SoFunction
Updated on 2024-11-16

Python function base examples [function nesting, namespaces, function objects, closures, etc.].

This article example describes the basic usage of Python functions. Shared for your reference, as follows:

I. What are named keyword parameters?

Format: Parameters after * are named keyword parameters.

Features:

1, the caller of the constraint function must pass the value according to the form Kye=value.

2. The caller of the constraint function must use the Key name we specified.

def auth(*args,name,pwd):
  print(name,pwd)
auth(pwd='213',name='egon')
def register(name,age):
  print(type(name),type(age))
register(123,[1,2,3])

Above output:

egon 213
<class 'int'> <class 'list'>

II. Nesting of functions

1, the function of the nested call: in the function and call other functions

def max2(x,y):
  if x > y:
    return x
  else:
    return y
def max3(x,y,z):
  res1=max(x,y)
  res2=max(res1,z)
  return res2
print(max3(88,99,100))

Above output:

100

2, the function of the nested definition: in the function and define other functions.

def func1():
  print('from func1')
  def func2(): #func2 = memory address
    print('from func2')
  print(func2) #<function func1.<locals>.func2 at 0x0000024907A098C8>
  func2()
  func2()
  func2()
func1()

Above output:

from func2
from func2
from func2

III. Namespaces for functions

1、Namespace:Store the name and value binding relationship of the place

x=888888888
def func():
  pass

2. The namespace is divided into three categories

(1) Built-in namespace: stores the names that come with the python interpreter, which take effect when the interpreter is started and expire when the interpreter is shut down.

(2) Global namespace: a file-level name that takes effect when the file is executed and expires at the end of the file or if the file is deleted during execution.

x=1
def f1():
  def f2():
    print(x)
  f2()
f1()
if 10 > 3:
  y=33333
while True:
  xxxxx=123123123

Above output:

1

(3) local name space: store the function's customized name (the function's parameters as well as the name of the function are stored with the local name space), temporarily effective when the function is called, the end of the function is invalid.

Attention:

Loading order: built-in namespace -------->>global namespace ------->>>local namespace

Find names: local namespace -------->>global namespace ------->>>built-in namespace

def f1():
  # len=1
  def f2():
    # len=2
    print(len)
  f2()
f1()

Above output:

global

3. Scope

Global scope: wrapped in the name of the built-in namespace and the global namespace.

Features:

  • (1) Accessible from any location
  • (2) Names in this scope stay with the program throughout its life cycle

Local scope: contains the name of a local namespace

Features:

  • (1) Use only within functions
  • (2) Effective when the function is called, invalid at the end of the call.

IV. Function Objects

1. Functions are the first class of objects in python

(1) Can be cited

x=1
y=x
def bar():
  print('from bar')
f=bar
f()

Above output:

from bar

(2) Can be passed in as a parameter

x=1
def func(a):
  print(a)
func(x)

Above output:

1

(3) Can be used as the return value of a function

Code (1)

x=1
def foo():
  return x
res=foo()
print(res)

Above output:

1

Code (2)

def bar():
  print('from bar')
def foo(func): #func=<function bar at 0x00000225AF631E18>
  return func #return <function bar at 0x00000225AF631E18>
# print(bar)
f=foo(bar) #f=<function bar at 0x00000225AF631E18>
# print(f)
f()

Above output:

from bar

(4) Elements that can be used as container types

x=1
l=[x,]
print(l)
def get():
  print('from get')
def put():
  print('from put')
l=[get,put]
# print(l)
l[0]()

Above output:

[1]
from get

Attention:

1. func can be referenced

f=func

2. func can be passed as an argument to x

3, func can also be used as a return value

4, can be used as a container in the type of elements

The function queries for references to the login function:

def auth():
  print('Please log in:')
def reigster():
  print('Registration:')
def search():
  print('View:')
def transfer():
  print('Transfers')
def pay():
  print('Payment')
dic={
  '1':auth,
  '2':reigster,
  '3':search,
  '4':transfer,
  '5':pay
}
def interactive():
  while True:
    print('''
    1 Authentication
    2 Registration
    3 View
    4 Transfer
    5 Payment
    '''
    )
    choice = input('Please enter the number:').strip()
    if choice in dic:
      dic[choice]()
    else:
      print('Illegal operation')
interactive()

V. Closure Functions

Closure: refers to a function defined inside a function

Scope relationships, which are defined at the function definition stage, have nothing to do with where the call is made.

def outter():
  x=2
  def inner():
    # x=1
    print('from inner',x)
  return inner
f=outter() #f=inner
def foo():
  x=1111111111111111111111111111
  f()
foo()

Above output:

from inner 2

1. closure function:

(1) Functions defined inside functions

(2) and the function contains a reference to a name in an external function scope, the function is called a closure function

Understand:

Ways to pass values to function bodies

Way 1: Pass in the value as a parameter.

Use a crawler to get the source code of a website:

import requests:
def get(url):
  response=(url)
  if response.status_code == 200:
    print()
get('')

Mode 2

import requests
import time
def outter(url): #url=''
  # url=''
  def get():
    response=(url)
    if response.status_code == 200:
      print()
  return get
baidu=outter('')
python=outter('')
baidu()
print('=====================>')
(3)
baidu()

For those interested in Python-related content, check out this site's feature: theSummary of Python function usage tips》、《Python Object-Oriented Programming Introductory and Advanced Tutorials》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python string manipulation techniques》、《Summary of Python coding manipulation techniquesand thePython introductory and advanced classic tutorials

I hope that what I have said in this article will help you in Python programming.