【问题标题】:Passing a variable to a child function without using it as an argument in Python将变量传递给子函数而不将其用作 Python 中的参数
【发布时间】:2020-09-05 07:03:57
【问题描述】:

我在 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 中。具体来说,它们的用例与我所追求的相同:

上下文提供了一种通过组件树传递数据的方法,而无需在每个级别手动向下传递道具。

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

这在 Python 中是否可能以某种方式实现?

【问题讨论】:

  • 如果您不想发送,请将context 保存在全局变量中。此时context是局部变量,你不能从其他函数访问它。

标签: python python-3.x


【解决方案1】:

一个类似乎非常适合给一个函数“上下文”:

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)

【讨论】:

    【解决方案2】:

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

    示例:

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

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

    【讨论】:

      【解决方案3】:

      使用 OOP,您可以这样做:

      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)
      

      结果

         a
       b
       c
       [1, 5]
      

      【讨论】:

        猜你喜欢
        • 2015-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多