函数内的函数 Python [英] A function inside a function Python

查看:64
本文介绍了函数内的函数 Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是之前问过的问题,但我无法真正理解此类问题的其他解释,因此我在这里重新编写更详细的内容.在学习的过程中,我遇到过这种我完全不熟悉的代码..我无法理解如何在 f() 函数中解释这个 g() 函数!为什么 g() 中 x = 10 和 y = z*w 的代码没有运行?它只打印给我的 y 值,用 5 调用 f() !

x = 99定义 f(y):w = x + y定义 g():x = 10y = z * w打印 yf(5)

解决方案

在 Python 中,def 是一个语句:接受一个函数名,可能是参数,然后是一个缩进的函数体——编译所有这些到一个函数对象中,它绑定到 def 出现的范围内的给定名称(这里是 f 的本地).

所以你问为什么 g() 中 x = 10 和 y = z*w 的代码不能运行"——很简单,因为你从不调用 g

gf 本地的这一事实(或者也称为嵌套在 f 中")并不是密切相关的.>

无论是局部的还是全局的,只要你def g,然后从不调用gg 主体中的代码将不会执行.

顺便说一句,这是 Python 与我听说过的所有其他语言相吻合的一个细节.如果一个函数被定义(一些语言称之为声明")并且从不被调用,那么函数的主体代码永远不会运行.你有没有听说过有其他语言这样做——即执行一个定义但从未调用过的函数的代码体?!

This is a problem asked before but I can't really understand the other explain of this kind of problem so I'm here to re-write it in more details. While studying I have encountered this kind of code that I am not at all familiar .. I can not understand how to interpret this g() function in f() function ! Why the piece of code inside g() where x = 10 and y = z*w does not run ? It's only print me the value of y I gave, calling f() with 5 !

x = 99

def f(y):
    w = x + y
    def g():
        x = 10
        y = z * w
    print y

f(5)

解决方案

In Python, def is a statement: takes a function name, possibly arguments, then an indented function body -- compiles it all into a function object, which it binds to the given name in the scope where def appeared (here, locally to f).

So you ask "Why the piece of code inside g() where x = 10 and y = z*w does not run" -- very simply, because you never call g!

The fact that g is local to f (or as is also known "nested in f") is not germane.

Whether local or global, anytime you def g but then never call g, the code in g's body will not execute.

Incidentally, this is a detail in which Python coincides with every other language I've ever heard about. If a function is defined (some languages call that "declared") and never called, then the function's body code never runs. Have you ever heard of any language doing otherwise -- i.e, executing the code body of a function that's defined but never called?!

这篇关于函数内的函数 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆