在Python中将变量传递给子函数而不将其用作参数

2024-07-03 05:53:48 发布

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

我在Python中有一个调用子函数的父函数。我希望能够在父函数中定义一个可以从子函数访问的变量,,而不必将其作为参数传递

这是因为子函数签名必须保持稳定,才能保持与大量代码的兼容性。此外,我的实际用例涉及到可能有数百个函数调用的大型调用堆栈,在每个函数调用中传递这个参数似乎很痛苦

我想做的是这样的:

def parent():
    context = [1]
    child(a, b, c)

def child(a, b, c):
    # Somehow access the context here, without it being an explicit argument
    context = get_context()
    context.append[5]

我在这里试图重新创建的内容与React Contexts类似,但是是Python。具体来说,它们的用例与我所追求的相同:

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

我曾考虑过使用上下文管理器(with x),但这实际上并没有提供子对象访问上下文的机制。我也不能在这里使用全局变量或类变量,因为我需要支持多个相互独立的调用堆栈

在Python中,这在某种程度上是可能的吗


Tags: theto函数代码child定义堆栈def
3条回答

类似乎非常适合提供函数“上下文”:

class Foo:
    def __init__(self, context):
        self.context = context

    def child(self, a, b, c):
        self.context …

def parent():
    foo = Foo([1])
    fun.child(a, b, c)

    # even:
    # child = foo.child
    # child(a, b, c)

我建议在子函数中添加一个默认变量,并检查该变量的值是否为None

例如:

def parent():
    context = [1]
    child(a, b, c, context)

def child(a, b, c, context = None):
    if context:   
        context.append[5]

使用默认变量作为最后一个参数将保留与所有以前实现的兼容性

With OOP, you can do this:

class ParentClass:
    context = [1,]
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def printname(self):
        print(self.a, self.b)

class Childclass(ParentClass):
    def __init__(self, a, b, c, my_context):
        super().__init__(a, b, c)
        ParentClass.context.append(my_context)

要将5附加到上下文并为a、b和c赋值,请执行以下操作:

x = Childclass('a', 'b', 'c', 5)
print(x.a, '\n', x.b, '\n', x.c, '\n', x.context)

Result

   a
 b
 c
 [1, 5]

相关问题 更多 >