如何在Python函数中给出局部变量的值?

时间:2017-08-10 11:21:46

标签: python function local-variables

我有以下功能:

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
>>>

3 个答案:

答案 0 :(得分:2)

有几种方法可以做到:

  1. 删除函数参数,它们将自动从全局范围中选取。阅读:Short Description of the Scoping Rules?
  2. user = "some text"
    key = "some numbers"
    
    def ex(filter):
        login = user
        secret = key
    
    1. 为它们提供静态默认值,或使用全局变量选择默认值。
    2. 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
      
      1. 请勿修改此功能,并使用部分功能,并应用userkey
      2. 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):在此之前定义用户和键并使用函数中的变量..如果在函数内找不到变量那么它将在封闭范围内搜索,然后在全局中搜索范围然后在内置函数中,如果您不想更改函数内部的全局变量,那么在使用变量名之前不需要使用全局变量

enter image description here  像这样打电话

 #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)

enter image description here

更新2

确定然后定义变量

 #file listdir.py
def ex(filter):
    login = user
    secret = key
    f1 = filter 
    print(login)
    print(secret)

enter image description here

答案 2 :(得分:0)

将函数定义为def ex(filter):

如果在本地范围内找不到全局变量,该函数将自动拾取全局变量(感谢Ashwini指出您不需要使用global)。因此,您可以将函数定义为:

def ex(filter):
    login = user
    secret = key
    f1 = filter 
    "..." #many other comands

然后在调用它时,只需传入filteruserkey将从全局范围中获取。所以可以打电话:

ex("2017/10")