如何在一个函数中将同一变量与另一个函数一起使用,而不将该变量设置为全局变量?
如何从一个函数中获取一个变量并在另一个函数中使用它,而不必将该变量设置为全局变量?
How can I take one variable from one function and use it in another function without having to make that variable global?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你基本上有两个选择。
一种是将其作为参数传递给第二个函数。 (如果您希望第一个函数看到值的更改,它需要是引用类型(例如字典/列表),并且您必须不覆盖该对象,只能修改它(例如
a.append(b )
而不是a = a + [b]
)。第二个是定义一个可以用作单例的类,从技术上讲,这仍然是“全局”定义的。它可以让你将事物分组:(
你也可以使用
dict
而不是类来执行此操作;这取决于偏好。)You have basically two choices.
One is to pass it to the second function as a parameter. (If you want the first function to see changes to the value, it needs to be a reference type (e.g. a dict/list) and you have to not overwrite the object, only modify it (e.g.
a.append(b)
rather thana = a + [b]
).The second is to define a class that can be used as a singleton. Technically, this is still defining something 'globally', but it lets you keep things grouped:
(You could also do this with a
dict
instead of a class; matter of preference.)让函数接受一个参数,并将该参数传入。
have the function take a parameter, and pass that parameter in.
技术上可行并且可以使用,例如用于记忆(但它通常隐藏在装饰器后面,并且只有那些确信自己做了正确的事情的人才能实现,即使他们可能仍然对此感到有点不好):
Technically possible and may be used, e.g. for memoisation (but then it is usually hidden behind a decorator and only implemented by people who are sure they do the right thing even though they might still feel a bit bad about it):
您可以使用闭包来处理此问题,或者更自然的是将两个函数定义为类的方法,并将“全局”变量定义为类的成员。
You can use closure to handle this, or more natural is to define both functions as methods of a class and the "global" variable as member of the class.