Py学习  »  Python

Python create函数在调用它的函数中自动创建变量?

user8714896 • 3 年前 • 1561 次点击  

假设这个函数有很多变量设置:

def set_variables():
    var_a = 10
    var_b = 200

这些变量需要在多个函数中设置,并通过变量名访问。有没有办法在调用调用它的父函数后创建这个函数s.t var_a var_b 不用还吗?上面的函数就是一个例子,但实际上有很多变量,所以下面这样的函数是不可行的。

def parent_function():
   var_a, var_b, ... = set_variables()

理想情况下我想要

def parent_function():
   set_variables()
   # do some code with var_a or var_b

或者甚至可能还一份口述 key , val 并自动生成 钥匙 名称设置为 瓦尔 .

比如说

def parent_function():
    var_dict = set_variables()
    some_func_to_auto_set_vars_from_dict(var_dict)
    # Do something with var_a or var_b
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130219
文章 [ 2 ]  |  最新文章 3 年前
xtofl
Reply   •   1 楼
xtofl    4 年前

让所有函数设置所有变量似乎很容易。但事实证明,这种隐性共享状态已成为维护工作的噩梦。

相反,使用不可变的数据类;它们或多或少地提供了您所要求的便利,但允许对代码进行更简单的推理。

@dataclass
class Settings:
  a: str =""
  b: int =5
  ...

def parent():
  s = initialize(Settings(c=[1,2,3]))
  use(s.a, s.b)
  ...

def initialize (s: Settings):
  return dataclass.replace(s,
      b=10, d="@#$_"
    )
Samwise
Reply   •   2 楼
Samwise    4 年前

返回一个集合,允许您按名称访问值,而无需重新分配它们,例如dict:

def set_variables():
    return {
        'a': 10,
        'b': 200,
    }
def parent_function():
   v = set_variables()
   # do some code with v['a'] or v['b']

或者(我个人对这个用例的偏好)a NamedTuple ,这为您提供了类型检查的好处(以及IDE自动完成,就像您使用顶级命名变量一样):

from typing import NamedTuple

class Vars(NamedTuple):
    a: int
    b: int

def set_variables() -> Vars:
    return Vars(a=10, b=200)

def parent_function():
    v = set_variables()
    # do some code with v.a and v.b