在函数中定义的调用函数

2024-06-16 19:03:00 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

def function1():
    def function2():
        print 'function2 has been called'
    def function3():
        pass

函数1允许我按顺序调用函数2和函数3。 但是如何从function1外部调用function2或function3呢?在

我尝试了,但没有成功:

^{pr2}$

以及:

import function1
function1.function2()

Tags: 函数代码importdefpasshasprintbeen
3条回答

如果需要function2和function3作为内部函数(因为它们使用function1的局部变量,但没有作为参数传递给f2或f3,或者其他原因),请编写一个返回函数的函数。在

功能:

def function1(a,b):
    c = a+b
    d = a*b*c
    def function2(d):
        print c+d
    def function3():
        pass
    function2(d)

相当于:

^{pr2}$

这允许您在function1内部和外部创建和使用function2。在

不能调用嵌套函数。它们仅对function1()是本地的。在

或者调用函数中的来获取它们的名字。在

另一个函数中的函数对象与任何其他局部变量类似,仅对该函数私有。在

作为全局变量:

def function2():
    print 'function2 has been called'

def function3():
    pass

def function1():
    # call the other functions
    function2()
    function3()

你需要创建可以类的模块

class MySuperClass:
    def function2(self):
        print 'function2 has been called'
    def function3(self, someArg):
        print 'function3 has been called with argument: '+ someArg

Python docs

相关问题 更多 >