【问题标题】:Python: understanding function orderPython:理解函数顺序
【发布时间】:2018-03-07 09:03:30
【问题描述】:

我通常会写出可耻的糟糕的代码,但这次我改变了主意,我想了解 Python 函数。

所以我正在尝试重写过去的一些脚本。我不明白为什么这段代码不执行:

import requests                                                             # 
import json

def Status_OK():        
    for SQL_element in response_data1['results']:
        SQL_Place_ID = SQL_element['place_id']

def get_place_for_show():                                                                                   
    url1 = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?types=movie_theater&location=-36.86667,174.76667&radius=25000&key=MyGoogleKey'                                                                     
    response1 = requests.get(url = url1)                                                            
    response_data1 = response1.json()

    if response_data1['status'] == 'OK':
        Status_OK()

get_place_for_show()

我的 HAL9000 回复这个错误:

Traceback (most recent call last):
  File "Test.py", line 16, in <module>
    get_place_for_show()
  File "Test.py", line 14, in get_place_for_show
    Status_OK()
  File "Test.py", line 5, in Status_OK
    for SQL_element in response_data1['results']:
NameError: name 'response_data1' is not defined

什么? NameError: name 'response_data1' 没有定义?

上面定义了一行!

该代码应该只打印 Google Place_ID 的列表,我知道该代码有效,因为我在另一个脚本上使用它但没有函数

【问题讨论】:

  • response_data1get_place_for_show() 中的一个局部变量。它在Status_OK() 中不可用。您需要将其作为参数传递给函数。
  • 你需要了解变量作用域。

标签: python json function google-maps-api-3


【解决方案1】:

变量是函数的局部变量。如果你想在多个函数中使用它,要么在函数调用中传递它,要么在更广泛的范围内定义它。

您可以查看函数中可用的变量

>>> get_place_for_show.__code__.co_varnames
('url1', 'response1', 'response_data1')

现在让我们看看它在 Status_OK 函数中的样子

>>> Status_OK.__code__.co_varnames
('SQL_element', 'SQL_Place_ID')

这就是你得到 NameError 异常的原因;该函数没有该属性(参数、参数、本地)。修复它:

import requests                                                             # 
import json

response_data1 = {}

def Status_OK():        
    for SQL_element in response_data1['results']:
        SQL_Place_ID = SQL_element['place_id']

def get_place_for_show():                                                                                   
    url1 = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?types=movie_theater&location=-36.86667,174.76667&radius=25000&key=MyGoogleKey'                                                                     
    response1 = requests.get(url = url1)                                                            
    response_data1 = response1.json()

    if response_data1['status'] == 'OK':
        Status_OK()

get_place_for_show()

【讨论】:

  • 该脚本与您的一些代码和@hspandher 代码一起工作。非常感谢你教会了我一些全新的东西
【解决方案2】:

response_data1 是函数get_place_for_show 中的一个局部变量。仅仅因为您在其中调用了Status_OK,并不意味着它会(或应该)共享get_place_for_show 的范围。尝试阅读scopes in Python

现在,如果您期待一些类似 closure 的行为,您需要在第一个函数中定义另一个函数。

def get_place_for_show():
    ...
    response_data1 = response1.json()

    def Status_OK():        
        for SQL_element in response_data1['results']:
            SQL_Place_ID = SQL_element['place_id']

    Status_OK()
    # Now it won't at least raise an error.
    ...

话虽如此,这只是出于演示目的,我在这里看不到任何实例化closure 的用例。

【讨论】:

  • 脚本使用了你的一些代码和@Vinny 代码。非常感谢你教会了我一些全新的东西
  • @FrancescoMantovani 很高兴,它有帮助。
【解决方案3】:

关于标准问题变量占空比的一点理论: var 在函数中创建时,会在函数中的最后一条语句执行后得到 DESTROYED。您需要将 var 的值 PASS 传递给函数,这样:

def Status_OK(response_data1):        
    for SQL_element in response_data1['results']:
        SQL_Place_ID = SQL_element['place_id']

然后这样调用:

Status_OK(somevar)

您的完整工作代码是:

import requests, json

def Status_OK(response_data1):        
    for SQL_element in response_data1['results']:
        SQL_Place_ID = SQL_element['place_id']

def get_place_for_show():                                                                                   
    url1 = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?types=movie_theater&location=-36.86667,174.76667&radius=25000&key=MyGoogleKey'                                                                     
    response1 = requests.get(url = url1)                                                            
    response_data1 = response1.json()

    if response_data['status'] == 'OK':
        Status_OK(response_data1)

get_place_for_show()

【讨论】:

    猜你喜欢
    • 2014-10-08
    • 2018-08-05
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多