繁体   English   中英

python 自动将变量传递给 function

[英]python automatically pass variables to function

我有这样的代码

def function3():
    print(text)

def function2():
    text = "Hello"
    function3()

def function1():
    text = "World"
    function3()

就像您看到的那样,我想将变量从函数 2 和函数 1 自动传递给函数 3。 这个变量应该只在这三个函数上可见(所以我不能将它设置为全局)。 另外我不想每次都在圆括号之间传递这个变量,因为我会使用 function3 数千次。 php 中是否有类似关键字的使用?

function3() use (text):
    print(text)

我不是 100% 确定我现在想要做什么(不知道 php),但它只是这样吗?

def function3(text):
    print(text)

def function2():
    text = "Hello"
    function3(text)

def function1():
    text = "World"
    function3(text)

没有什么直接等效的,您通常只需传递 arguments 即可。

据我了解,PHP 中的use关键字可手动将变量添加到匿名函数的闭包中。 在 python 中,function 范围已经使用词法范围规则自动为您创建了闭包。 你可以这样做:

def function_maker():
    text = None # need to initialize a variable in the outer function scope
    def function3():
        print(text)

    def function2():
        nonlocal text
        text = "Hello"
        function3()

    def function1():
        nonlocal text
        text = "World"
        function3()

    return function1, function2, function3

function1, function2, function3 = function_maker()

但是这种模式在 Python 中并不常见,您只需使用 class:

class MyClass:
    def __init__(self, text): # maybe add a constructor
        self.text = text

    def function3(self):
        print(self.text)

    def function2(self):
        self.text = "Hello"
        self.function3()

    def function1(self):
        self.text = "World"
        self.function3()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM