第十六-十七章 Functions and Generators

第十六章 Function Basics

Coding Functions

  • def is executable code.:函数可嵌套
  • def creates an object and assigns it to a name.:function object,function name.
  • lambda creates an object but returns it as a result.
  • return sends a result object back to the caller.
  • yield sends a result object back to the caller, but remembers where it left off
  • global declares module-level variables that are to be assigned.
  • nonlocal declares enclosing function variables that are to be assigned.
  • Arguments are passed by assignment (object reference).
  • Arguments are passed by position, unless you say otherwise
  • Arguments, return values, and variables are not declared.

def name(arg1, arg2,... argN):
...
return value

第十七章 Scopes


function’s namespace


three different scopes:

  • If a variable is assigned inside a def, it is local to that function.
  • If a variable is assigned in an enclosing def, it is nonlocal to nested functions.
  • If a variable is assigned outside all defs, it is global to the entire file.



Comprehension variables:in 3.X, such variables are local to the expression itself in all comprehension forms: generator, list, set, and dictionary.



y, z = 1, 2 # Global variables in module
def all_global():
    global x # Declare globals assigned
    x = y + z # No need to declare y, z: LEGB rule

all_global()
print(x)  #输出3


# thismod.py
var = 99 # Global variable == module attribute

def local():
    var = 0 # Change local var
    
def glob1():
    global var # Declare global (normal)
    var += 1 # Change global var

def glob2():
    var = 0 # Change local var
    import thismod # Import myself
    thismod.var += 1 # Change global var

def glob3():
    var = 0 # Change local var
    import sys # Import system table
    glob = sys.modules['thismod'] # Get module object (or use __name__)
    glob.var += 1 # Change global var

def test():
    print(var)
    local(); glob1(); glob2(); glob3()
    print(var)



E layer:the local scopes of any and all enclosing function’s local scopes. 或statically nested scopes



def f1():
    X = 88
    def f2():
        print(X) # Remembers X in enclosing def scope
    return f2 # Return f2 but don't call it

action = f1() # Make, return function
action() # Call it now: prints 88

Factory Functions: Closures:

def maker(N):
    def action(X): # Make and return action
        return X ** N # action retains N from enclosing scope
    return action

f = maker(2)
print(f,f(3),f(4))

>>> ================================ RESTART ================================
>>> 
<function maker.<locals>.action at 0x000000000080CBF8> 9 16


def f1():
    x = 88 # Pass x along instead of nesting
    f2(x) # Forward reference OK

def f2(x):
    print(x) # Flat is still often better than nested!

f1()
>>> ================================ RESTART ================================
>>> 
88

def makeActions():
    acts = []
    for i in range(5): # Tries to remember each i
        acts.append(lambda x: i ** x) # But all remember same last i!
    return acts

acts = makeActions()
print(acts[0],acts[0](2),acts[1](2),acts[2](2),acts[3](2),acts[4](2),sep='\n')


<pre name="code" class="python">>>> ================================ RESTART ================================
>>> 
<function makeActions.<locals>.<lambda> at 0x000000000276CBF8>
16
16
16
16
16

 

def makeActions():
    acts = []
    for i in range(5): # Use defaults instead
        acts.append(lambda x, i=i: i ** x) # Remember current i
    return acts

acts = makeActions()
print(acts[0],acts[0](2),acts[1](2),acts[2](2),acts[3](2),acts[4](2),sep='\n')

>>> ================================ RESTART ================================
>>> 
<function makeActions.<locals>.<lambda> at 0x0000000002E6CBF8>
0
1
4
9
16

The nonlocal Statement in 3.X:

def func():
nonlocal name1, name2, ... # OK here
>>> nonlocal X
SyntaxError: nonlocal declaration not allowed at module level

  • global makes scope lookup begin in the enclosing module’s scope and allows
    names there to be assigned. Scope lookup continues on to the built-in scope if the
    name does not exist in the module, but assignments to global names always create
    or change them in the module’s scope.
  • nonlocal restricts scope lookup to just enclosing defs, requires that the names already
    exist there, and allows them to be assigned. Scope lookup does not continue
    on to the global or built-in scopes.



def tester(start):
    state = start # Each call gets its own state
    def nested(label):
        nonlocal state # Remembers state in enclosing scope
        print(label, state)
        state += 1 # Allowed to change it if nonlocal
    return nested
>>> F = tester(0)
>>> F('spam') # Increments state on each call
spam 0
>>> F('ham')
ham 1
>>> F('eggs')
eggs 2

>>> G = tester(42) # Make a new tester that starts at 42
>>> G('spam')
spam 42
>>> G('eggs') # My state information updated to 43
eggs 43
>>> F('bacon') # But F's is where it left off: at 3
bacon 3

First, unlike the global statement, nonlocal names really must have previously been assigned in an enenclosing
def’s scope when a nonlocal is evaluated, or else you’ll get an error
def tester(start):
    def nested(label):
        global state # Nonlocals must already exist in enclosing def!
        state = 0
        print(label, state)
    return nested

 SyntaxError: no binding for nonlocal 'state' found

def tester(start):
    def nested(label):
        global state # Globals don't have to exist yet when declared
        state = 0    # This creates the name in the module now
        print(label, state)
    return nested


>>> F = tester(0)
>>> F('abc')
abc 0
>>> state
0

Second, nonlocal restricts the scope lookup to just enclosing defs;



State with nonlocal: 3.X only:


State with Globals: A Single Copy Only:


State with Classes: Explicit Attributes (Preview):



State with Function Attributes: 3.X and 2.X:




State with mutables: Obscure ghost of Pythons past?:








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: @babel/plugin-transform-async-to-generator是一个Babel插件,它将async/await语法转换为ES5代码,以便在不支持该语法的环境中运行。要配置该插件,请按照以下步骤操作: 1. 安装@babel/plugin-transform-async-to-generator插件: ``` npm install --save-dev @babel/plugin-transform-async-to-generator ``` 2. 在babel配置文件中添加该插件: ```javascript { "plugins": ["@babel/plugin-transform-async-to-generator"] } ``` 3. 如果您使用的是babel 7及以上版本,可以将插件配置为使用"options"选项: ```javascript { "plugins": [ ["@babel/plugin-transform-async-to-generator", { "module": "bluebird", "method": "coroutine" }] ] } ``` 这里的例子展示了如何使用bluebird库中的coroutine方法来提供async/await功能。您可以使用其他库或方法来实现相同的效果。 注意:如果您使用的是babel 6.x版本,则需要在插件名称前添加"babel-"前缀,例如"babel-plugin-transform-async-to-generator"。 ### 回答2: @babel/plugin-transform-async-to-generator是一个Babel插件,用于将ES7中的`async/await`转换为ES6中的生成器函数。要配置该插件,您需要按照以下步骤进行操作: 1. 首先,安装插件,通过运行以下命令:`npm install --save-dev @babel/plugin-transform-async-to-generator`。 2. 在项目的根目录下创建一个名为`.babelrc`的文件(如果它不存在)。这是Babel的配置文件。 3. 在`.babelrc`文件中,添加以下内容: ```json { "plugins": ["@babel/plugin-transform-async-to-generator"] } ``` 这指示Babel加载并使用@babel/plugin-transform-async-to-generator插件。 4. 如果您使用的是Babel 7以上的版本,可以在`.babelrc`中指定插件的参数。例如,要指定`regenerator`作为插件的参数(用于支持较旧的浏览器),您的`.babelrc`文件应如下所示: ```json { "plugins": [ ["@babel/plugin-transform-async-to-generator", { "regenerator": true }] ] } ``` 这样配置后,Babel将在转换代码时使用@babel/plugin-transform-async-to-generator插件,并根据需要设置生成器函数的参数。 请注意,配置文件`.babelrc`的路径可以根据您的项目结构和工具链的不同而有所不同。记得根据您的实际情况,根据需要设置正确的路径。 希望这能帮到您!如果您有其他问题,请随时提问。 ### 回答3: @babel/plugin-transform-async-to-generator是一个可以将async/await语法转换成generator函数的Babel插件。要配置该插件,你需要按照以下步骤进行操作: 第一步,安装插件: ``` npm install --save-dev @babel/plugin-transform-async-to-generator ``` 第二步,在你的babel配置文件(如.babelrc)中添加插件的相关配置: ```json { "plugins": ["@babel/plugin-transform-async-to-generator"] } ``` 或者,如果你使用的是babel.config.js,可以按照以下方式进行配置: ```javascript module.exports = { plugins: ['@babel/plugin-transform-async-to-generator'] } ``` 完成以上配置后,插件会自动转换你的async/await语法成generator函数,使之能够在不支持async/await的环境中运行。 注意,插件的配置选项是可选的,你可以根据需要进行进一步配置。你可以在插件配置中指定一个"module"选项,该选项用于控制生成的模块类型,可选的值为"commonjs"和"amd"。默认值为"commonjs"。 希望以上回答能够帮助到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值