如何在类中的另一个函数中更新变量?

时间:2014-10-15 20:42:40

标签: python python-2.7

我有一个包含一些函数的类,在我的change_date函数中,我需要重新分配self.date中的__init__变量。但是,最初,我需要self.date = yesterday(),如何从其他功能重新分配这个功能,然后继续使用新日期__init__的流程?

class PVData:
    def __init__(self):
        self.date = yesterday()
        self.data = load_data(self.date)

        #time, temp, sun
        self.time = []
        self.temperature = []
        self.sunlight = []
        self.powerlist = [] ####LIST OF ALL POWER TUPLES FOR DAY
        for minute in self.data:
            self.time.append(minute[0])
            self.temperature.append(minute[1])
            self.sunlight.append(minute[2])
            self.powerlist.append(minute[3])
        ##power

        self.placelist = []
        for i in ARRAYS:
            self.placelist.append(i)

        ##Combine lists to dictionary with loop
        self.dictionary = {}
        self.dictionary = dict(zip(self.placelist, self.powerlist)) 




def change_date(self, date):
        if self.date != date:
            self.date = date
            self.__init__()           
            #self.refresh()
        else:
            self.date = date

1 个答案:

答案 0 :(得分:1)

通常,您希望将大多数__init__逻辑重构为不同的函数,例如:使用_initialize设置其他内容的self.date ...

class PVData(object):
    def __init__(self):
        self.date = yesterday()
        self._initialize()

    def change_date(self, date):
        if self.date != self.date:
            self.date = date
            self._initialize()

    def _initialize(self):
        self.data = load_data(self.date)

        #time, temp, sun
        self.time = []
        self.temperature = []
        self.sunlight = []
        self.powerlist = [] ####LIST OF ALL POWER TUPLES FOR DAY
        for minute in self.data:
            self.time.append(minute[0])
            self.temperature.append(minute[1])
            self.sunlight.append(minute[2])
            self.powerlist.append(minute[3])
        ##power

        self.placelist = []
        for i in ARRAYS:
            self.placelist.append(i)

        ##Combine lists to dictionary with loop
        self.dictionary = {}
        self.dictionary = dict(zip(self.placelist, self.powerlist))