简体   繁体   中英

python automatically pass variables to function

I have code like this

def function3():
    print(text)

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

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

Like you see i want to automatically pass variable from function2 and function1 to function3. This variable should be visible only on this three functions (so I can't set it global). Also I don't want to pass this variable every time between round brackets, because I will use function3 thousands of times. Is there a something like keyword use in php?

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

I'm not 100% sure I now what you want to do (don't know php), but is it just something like this?

def function3(text):
    print(text)

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

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

There is nothing directly equivalent, you would normally just pass the arguments around.

From what I understand, the use keyword in PHP to manually add variables to an anonymous function's closure. In python, function scopes already create closures for you automatically using lexical scoping rules. You can do something like this:

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

But this pattern wouldn't be common in Python, you would just use a 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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