【问题标题】:python automatically pass variables to functionpython自动将变量传递给函数
【发布时间】:2020-06-01 09:46:30
【问题描述】:

我有这样的代码

def function3():
    print(text)

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

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

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

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

【问题讨论】:

标签: python function variables scope


【解决方案1】:

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

def function3(text):
    print(text)

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

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

【讨论】:

    【解决方案2】:

    没有什么直接等价的,你通常只是传递参数。

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

    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 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多