AttributeError: '模块'对象没有属性'YWeather
我看了很多问题,但似乎找不到解决办法。以下是我的文件结构:
Test.py 文件导入了 yahoo_weather,并希望使用 YWeather 类中的函数。
test/
test.py
yahoo_weather/
__init__.py
codes.csv
yahoo_weather.py
这是 yahoo_weather.py 中的代码:
import urllib.request
import xml.etree.ElementTree as etree
import csv
import os
class YWeather(object):
def __init__(self):
self.codes = self.readDict('codes.csv')
def translate_code(code):
return self.codes[code]
def weather_data(self, woeid, unit):
if unit != 'c' or unit !='f':
print('Weather unit: ' + unit + ' is not a valid unit type')
print('Weather unit must either be "c" or "f" for celcius or farenheit')
print('Assuming Farenheit')
url = 'http://weather.yahooapis.com/forecastrss?w=' + str(woeid) + '&u=' + unit
#print(url)
root = self.returnroot(url)
data = dict()
#Pull any useful information out of the xml
try:
data['language'] = root[0][3].text
data['location'] = root[0][6].attrib
data['units'] = root[0][7].attrib
data['day0_wind'] = root[0][8].attrib
data['day0_atmosphere'] = root[0][9].attrib
data['day0_astronomy'] = root[0][10].attrib
data['location_lat'] = root[0][12][1].text
data['location_long'] = root[0][12][2].text
data['yahoo_link'] = root[0][12][3].text
data['pubDate'] = root[0][12][4].text
data['day0_condition'] = root[0][12][5].attrib
#Get forecast data, today being day0
for i in range(0, 4):
data['day'+str(i)+'_forecast'] = root[0][12][i+7].attrib
except IndexError:
print("WOEID: " + str(woeid) + " Is not a valid WOEID")
return data
def readDict(self, file):
h = []
with open(file, 'r') as f:
reader = csv.reader(f)
for row in reader:
if row != []:
h.append(row)
return dict(h)
def returnroot(self, url):
try:
xmltext = (urllib.request.urlretrieve(url))
except:
print('Internet connection or WOEID is not valid')
root = (etree.parse(xmltext[0])).getroot()
global c
c = root
return root
在 test.py 中:
import yahoo_weather
yw = yahoo_weather.YWeather()
data = yw.weather_data(6, 'c')
当我运行 test.py 时,出现了这个错误:
Traceback (most recent call last):
File "/home/david/documents/test/test.py", line 2, in <module>
yw = yahoo_weather.YWeather()
AttributeError: 'module' object has no attribute 'YWeather'
__init__.py 文件是空的。
谢谢你的阅读!
1 个回答
2
你有一个叫做 yahoo_weather
的 包,这个包里面有一个叫 yahoo_weather
的 模块,而这个模块里包含了你的类。首先,你需要导入这个模块:
from yahoo_weather import yahoo_weather
这样你就可以使用 yahoo_weather.YWeather()
这个功能了。
另外,你也可以在 yahoo_weather/
这个文件夹里的 __init__.py
文件中添加一行代码:
from yahoo_weather import YWeather
然后就可以直接使用你之前写的代码了。