【问题标题】:Python issue value of property changes when falling out of loop scope超出循环范围时的Python问题属性值更改
【发布时间】:2016-01-05 08:04:59
【问题描述】:

我编写的 python 类有问题,具体问题出在 parseData() 函数中。

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

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

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

任何帮助将不胜感激该类如下所示,我插入的对象是我编写的一个简单的自定义类。

# 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

【问题讨论】:

    标签: python scope


    【解决方案1】:

    发生这种情况是因为您只创建了一个 WeatherData 类的实例,因此您只需一遍又一遍地更新同一个实例。

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

    【讨论】:

    • 哇,这很有意义,所以当我将 WeatherData 对象附加到列表时,它不会在列表中创建该对象的新副本,而只是指向该现有 weatherData 对象的链接?
    • 没错,您可以使用copy.deepcopy将对象的副本添加到您的列表中,但给定的解决方案比IMO要好得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 2011-09-07
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    相关资源
    最近更新 更多