个性化阅读
专注于IT技术分析

Python内部函数用法完整指南

本文概述

在Python中, 函数被视为第一类对象。一门语言中的一流对象始终都得到统一处理。它们可以存储在数据结构中, 可以作为参数传递, 也可以在控制结构中使用。如果一种编程语言将函数视为一流的对象, 则称其支持一流的功能。 Python支持First Class函数的概念。

一级函数的属性:

  • 函数是对象类型的实例。
  • 你可以将函数存储在变量中。
  • 你可以将该函数作为参数传递给另一个函数。
  • 你可以从函数返回函数。
  • 你可以将它们存储在哈希表, 列表等数据结构中。

注意:进一步了解一流的对象点击这里.

内部功能

在另一个函数中定义的一个函数称为内部功能or嵌套函数。嵌套函数能够访问封闭范围的变量。使用内部函数, 以便可以保护它们免受该函数外部发生的一切影响。此过程也称为封装形式。进一步了解封装点击这里.

例子:

# Python program to illustrate 
# nested functions 
def outerFunction(text): 
     text = text 
    
     def innerFunction(): 
         print (text) 
    
     innerFunction() 
    
if __name__ = = '__main__' : 
     outerFunction( 'Hey !' )

输出如下:

Hey!

在上面的示例中, 在innerFunction()内部定义了innerFunction(), 使其成为内部函数。要调用innerFunction(), 我们必须首先调用externalFunction()。然后, externalFunction()将继续进行, 并按照在其中定义的方式调用innerFunction()。

重要的是必须调用外部函数, 以便内部函数可以执行。为了说明这一点, 请考虑以下示例:

例子:

# Python program to illustrate 
# nested functions 
def outerFunction(text): 
     text = text 
    
     def innerFunction(): 
         print (text) 
    
     innerFunction()

输出如下:

This code will return nothing when executed.

嵌套函数中变量的范围

我们可以找到变量并在需要时访问它的位置称为变量的范围。

已知如何访问

全局变量

在函数内部, 但是, 如何访问外部函数的变量呢?让我们来看一个例子:

# Python program to 
# demonstrate accessing of
# variables of nested functions
  
def f1():
     s = 'I love srcmini'
      
     def f2():
         print (s)
          
     f2()
  
# Driver's code
f1()

输出如下:

I love srcmini

在上面的示例中, 可以看出它类似于从函数访问全局变量。现在, 假设你要更改外部函数的变量。

# Python program to 
# demonstrate accessing of
# variables of nested functions
  
def f1():
     s = 'I love srcmini'
      
     def f2():
         s = 'Me too'
         print (s)
          
     f2()
     print (s)
  
# Driver's code
f1()

输出如下:

Me too
I love srcmini

可以看出外部函数变量的值没有改变。但是, 可以更改外部函数的变量的值。有多种方法可以更改外部函数变量的值。

使用迭代

# Python program to 
# demonstrate accessing of
# variables of nested functions
  
def f1():
     s = [ 'I love srcmini' ]
      
     def f2():
         s[ 0 ] = 'Me too'
         print (s)
          
     f2()
     print (s)
  
# Driver's code
f1()

输出如下:

['Me too']
['Me too']

使用非本地关键字–

# Python program to 
# demonstrate accessing of
# variables of nested functions
  
def f1():
     s = 'I love srcmini'
      
     def f2():
         nonlocal s
         s = 'Me too'
         print (s)
          
     f2()
     print (s)
  
# Driver's code
f1()

输出如下:

Me too
Me too

值也可以更改, 如下例所示。

# Python program to 
# demonstrate accessing of
# variables of nested functions
  
def f1():
     f1.s = 'I love srcmini'
      
     def f2():
         f1.s = 'Me too'
         print (f1.s)
          
     f2()
     print (f1.s)
  
# Driver's code
f1()

输出如下:

Me too
Me too

Python闭包

闭包是一个函数对象, 即使在内存中不存在值, 它也会记住范围内的值。

  • 它是将功能与环境存储在一起的记录:一种映射, 该映射将功能的每个自由变量(在本地使用, 但在封闭范围内定义的变量)与在关闭时绑定名称的值或引用相关联已创建。
  • 与普通函数不同, 闭包允许该函数通过闭包的值或引用的副本访问这些捕获的变量, 即使该函数在其作用域之外被调用也是如此。
    filter_none。
# Python program to illustrate 
# closures 
def outerFunction(text): 
     text = text 
    
     def innerFunction(): 
         print (text) 
    
     return innerFunction # Note we are returning function WITHOUT parenthesis 
    
if __name__ = = '__main__' : 
     myFunction = outerFunction( 'Hey !' ) 
     myFunction()

输出如下:

Hey!
  • 从上面的代码可以看出, 闭包有助于在其范围之外调用函数。
  • 函数innerFunction仅在outerFunction内部具有范围。但是, 通过使用闭包, 我们可以轻松扩展其作用域以调用其作用域之外的函数。
# Python program to illustrate 
# closures 
import logging 
logging.basicConfig(filename = 'example.log' , level = logging.INFO) 
    
    
def logger(func): 
     def log_func( * args): 
         logging.info( 
             'Running "{}" with arguments {}' . format (func.__name__, args)) 
         print (func( * args)) 
     # Necessary for closure to work (returning WITHOUT parenthesis) 
     return log_func               
    
def add(x, y): 
     return x + y 
    
def sub(x, y): 
     return x - y 
    
add_logger = logger(add) 
sub_logger = logger(sub) 
    
add_logger( 3 , 3 ) 
add_logger( 4 , 5 ) 
    
sub_logger( 10 , 5 ) 
sub_logger( 20 , 10 )

输出如下:

6
9
5
10

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(0)
未经允许不得转载:srcmini » Python内部函数用法完整指南

评论 抢沙发

评论前必须登录!