【问题标题】:AttributeError: 'module' object has no attribute 'lat'AttributeError:“模块”对象没有属性“纬度”
【发布时间】:2017-11-28 13:00:26
【问题描述】:

apispy_m.py

def aspy_geolocate(api_spy_akey, api_spy_ytvid):
    function_name = "geolocate"
    function_description = """Get location of a youtube video!"""
    if api_spy_akey == "":
        errcode = 001
        aspy_errhandler(function_name, errcode)
    else:
        pass
    r = requests.get('https://www.googleapis.com/youtube/v3/videos?part=recordingDetails&id=%s&key=%s'%(api_spy_ytvid, api_spy_akey))
    api_spy_jsondata = json.loads(r.text)
    try:
        lat = api_spy_jsondata['items'][0]['recordingDetails']['location']['latitude']
        lon = api_spy_jsondata['items'][0]['recordingDetails']['location']['longitude']
        alt = api_spy_jsondata['items'][0]['recordingDetails']['location']['altitude']
    except KeyError:
        lat = "N/A"
        lon = "N/A"
        alt = "M/A"

模块测试.py

import apispy_m
api_spy_akey = "*Super secret api key ;)*"
api_spy_ytvid = "*youtube vid id*"
aspy = apispy_m
aspy.aspy_geolocate(api_spy_akey, api_spy_ytvid)
print aspy.lat
print aspy.lon
print aspy.alt

运行 testmodule.py 后出错(使用 Python2):

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    print aspy.lat
AttributeError: 'module' object has no attribute 'lat'

我似乎无法解决此错误。我已经尝试过from apispy_m import * 和from apispy_m import aspy_geolocate。这是我第一次创建 python 模块。

我们将不胜感激!

【问题讨论】:

  • lat 是一个局部变量。让你的函数返回那些值(作为一个元组)。

标签: python python-2.7 printing module attributeerror


【解决方案1】:

您在函数中设置了局部变量,而不是模块属性(全局)。局部变量对函数之外的任何人都是不可见的(当函数退出时它们抓住存在)。

您想要返回这些值:

try:
    lat = api_spy_jsondata['items'][0]['recordingDetails']['location']['latitude']
    lon = api_spy_jsondata['items'][0]['recordingDetails']['location']['longitude']
    alt = api_spy_jsondata['items'][0]['recordingDetails']['location']['altitude']
    return (lat, lon, alt)
except KeyError:
    return ("N/A", "N/A", "N/A")

(假设您想要返回 "N/A",如果缺少 3 个组件中的 任何)。

然后将这 3 个值分配给调用函数的代码中的三个新变量:

lat, lon, alt = aspy.aspy_geolocate(api_spy_akey, api_spy_ytvid)
print lat
print lon
print alt

【讨论】:

  • @ACiDRAiN:您是用我的代码替换代码中的print 调用还是将它们留在里面?
猜你喜欢
  • 2010-11-18
  • 2018-08-28
相关资源
最近更新 更多