超出循环范围时属性更改的 Python 问题值 [英] Python issue value of property changes when falling out of loop scope

查看:65
本文介绍了超出循环范围时属性更改的 Python 问题值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编写一个 python 类时遇到了问题,具体问题出在 parseData() 函数中.

I am having trouble with a python class i wrote, the particular problem is in the parseData() function.

在函数的最后,我评论了问题出在哪里.问题是,当我完成朝向 parseData() 函数底部的代码的内部循环时,self.listOfParsedWeatherData 的值是正确的,但是一旦范围超出第二个循环,self 中每个元素的值.listOfParsedWeatherData 是前一个元素的副本.

at the end of the function i have commented where the problem is. The problem is that when i finish the inner loop of the code towards the bottom of the parseData() function is run the value of self.listOfParsedWeatherData is correct, however once the scope falls out of the second loop the value of each element in self.listOfParsedWeatherData is a copy of the previous last element.

基本上,当我在第二个循环的范围内检查列表的值时,它会类似于 [0, 1, 2, 3, 4, 5] 但是当我检查相同列表之外的值时第二个循环它出现[5, 5, 5, 5, 5, 5].

Basically when i check the value of the list within the scope of the second loop it would be something like [0, 1, 2, 3, 4, 5] but when i check the value of the same list outside of the second loop it it comes up as [5, 5, 5, 5, 5, 5].

我确信它与作用域或深浅副本有关,但我对 python 语言仍然相当陌生,我不确定其中的一些复杂性.虽然我怀疑这个问题真的很复杂.

I am sure it has something to do with scopes or deep and shallow copies but I'm still fairly new to the python language and I'm not sure of some of the intricacies. Though i doubt the problem is something really complex.

非常感谢任何帮助,该类如下所示,我插入的对象是我编写的一个简单的自定义类.

Any help would be greatly appreciated the class is shown below and the object I'm inserting is a simple custom class that i wrote.

# imports
import pywapi                            # used to grab weather data from NOAA in a JSON format
import copy
from WeatherData import WeatherData     # import custom weatherdata object

import pprint 
pp = pprint.PrettyPrinter(indent=4)     # set up pretty printer object

##
## Class used for grabing and parsing weather data from 
## NOAA
##
class NOAAParser:
# initliazer for the NOAAParser class
def __init__(self):
    # stores the list of json city data
    self.listOfCityData = []

    # A list of weatherData
    self.listOfParsedWeatherData = []

##
## function to grab the weather and returns a JSON object of the weather data
##
## Parameters: self, dictionary of cities and their codes
##
def retrieveNOAAWeatherJson(self, cityCodes):
    # loop through city codes and append them to a list of 
    cityData = []

    # weather objects returned from pywapi
    for key, value in cityCodes.iteritems():
        cityData.append(pywapi.get_weather_from_noaa(value))

    # set the list of city json data 
    self.listOfCityData = cityData

##
## This function parses the listOfCityData and returns a list 
## of weatherData objects which can be displayed to the user
##
##
def parseData(self):
    # check if the listOfCities has been populated
    if not self.listOfCityData:
        return False

    else:
        # create a new object of weather data
        newWeatherData = WeatherData()

        # loop over list and parse the data
        for index in range(len(self.listOfCityData)):
            # loop over the dictionary values in the list
            for key, value in self.listOfCityData[index].iteritems():
                # grab weather Description key: "weather" (String)
                if key == "weather":
                    # print value
                    newWeatherData.weatherCondition = value

                # grab the location key: "location" (String)
                if key == "location":
                    # print value
                    newWeatherData.location = value

                # grab temp key: "temperature_string" (String)
                if key == "temperature_string":
                    # print value
                    newWeatherData.currentTemp = value

                # grab Humidity key: "relative_humidity" (Int)
                if key == "relative_humidity":
                    # print value
                    newWeatherData.humidity = value

                # grab wind direction key: "wind_dir" (String)
                if key == "wind_dir":
                    # print value
                    newWeatherData.windDirection = value

                # grab last updated time key: "observation_time" (String)
                if key == "observation_time":
                    # print value
                    newWeatherData.lastUpdated = value

            # append the new weather data object to the list
            self.listOfParsedWeatherData.append(newWeatherData)

            ## VALUE OF self.listOrParsedWeatherData is correct

    ## VALUE OF self.listOfParsedWeatherData is only the value of the last element 
    ## of the previous self.listOfParsedWeatherData (incorrect)

    # return success from the function
    return True

推荐答案

发生这种情况是因为您只创建了 WeatherData 类的单个实例,因此您只需不断更新相同的实例再次.

This is happening because you only ever create a single instance of the WeatherData class, so you just keep updating that same one over and over again.

您只需将 newWeatherData = WeatherData() 行移到第一个 for 循环内.

You just need to move the line newWeatherData = WeatherData() inside of your first for loop.

这篇关于超出循环范围时属性更改的 Python 问题值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆