我有以下功能:
def ex(filter, key, user):
login = user
secret = key
f1 = filter
"..." #many other comands
user = "some text"
key = "some numbers"
filter = "2017/10"
应用这个函数我写道:
user = "some text"
key = "some numbers"
ex("2010/10",key,user)
此功能可以正常运行。我的问题是如何使局部变量从全局变量中获取值? 所以我希望能够通过编写以下内容来应用我的代码:
user = "some text"
key = "some numbers"
ex("2017/10")
有什么建议吗?
更新
按照@v Sugumar的说法歪曲代码。从shell
>>> import expens as e
>>> user = "XXX"
>>> key = "111"
>>> e.exp("08/2017")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\ad\Anaconda4\lib\expens.py", line 29, in exp
userid = user
NameError: name 'user' is not defined
>>>
答案 0 :(得分:2)
有几种方法可以做到:
user = "some text"
key = "some numbers"
def ex(filter):
login = user
secret = key
user = "some text"
key = "some numbers"
def ex(filter, key="some numbers", user="some text"): # static defaults
def ex(filter, key=key, user=user): # defaults picked from global variables
user
和key
。
from functools import partial
ex_with_user_and_key = partial(ex, key="some numbers", user="some text")
ex_with_user_and_key("2017/10")
答案 1 :(得分:1)
只需创建函数def ex(filter):在此之前定义用户和键并使用函数中的变量..如果在函数内找不到变量那么它将在封闭范围内搜索,然后在全局中搜索范围然后在内置函数中,如果您不想更改函数内部的全局变量,那么在使用变量名之前不需要使用全局变量
#file listdir.py
def ex(filter):
login = user
secret = key
f1 = filter
print(login)
print(secret)
user = "some text"
key = "some numbers"
ex("2017/10")
更新
#file listdir.py
def ex(filter,user,key):
login = user
secret = key
f1 = filter
print(login)
print(secret)
更新2
确定然后定义变量
#file listdir.py
def ex(filter):
login = user
secret = key
f1 = filter
print(login)
print(secret)
答案 2 :(得分:0)
def ex(filter):
如果在本地范围内找不到全局变量,该函数将自动拾取全局变量(感谢Ashwini指出您不需要使用global
)。因此,您可以将函数定义为:
def ex(filter):
login = user
secret = key
f1 = filter
"..." #many other comands
然后在调用它时,只需传入filter
,user
和key
将从全局范围中获取。所以可以打电话:
ex("2017/10")