运行类中定义的函数

2024-05-29 02:29:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python类,其中包含一些信息。我有另一个文件,其中一些函数引用。我的get_date工作正常,但是我的其他函数似乎都没有工作。调用time函数时出现错误AttributeError: PVData instance has no attribute 'time'。你知道吗

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

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

        #time, temp, sun
        self.time = []
        self.temperature = []
        self.sunlight = []

        for minute in self.date:
            self.time.append(minute[0])
            self.temperature.append(minute[1])
            self.sunlight.append(minute[2])

        #power
        self.dictonary[a] = []

        for a in ARRAYS:
            self.dictionary[ARRAYS[i]].append(power)

    def get_date(self):
        return self.date

    def get_time(self, time_index):
        return self.time[time_index]

    def get_temperature(self):
        return self.temperature

    def get_sunlight(self):
        return self.sunlight

    def get_power(self, array):
        return self.dictionary[array]

pvd = PVData()

加载数据函数是(在另一个文件中):

def load_data(dateStr):
    text = get_data_for_date(dateStr)
    data = []

    for line in text.splitlines():
        time, temp, sun, powerStr = line.split(',', 3)

        power = []
        for p in powerStr.split(','):
            power.append(int(p))

        data.append((time, float(temp), float(sun), tuple(power)))

    return data

返回如下内容:

[('19:00', 20.0, 0.0, (0, 0, 0, 0, 0, 0, 0, 21, 31, 52)), (tuple 2), etc etc]

这个错误似乎是因为时间不是self的有效参数,但我认为它是在self.time = []处定义的。 请原谅我缺乏知识,python对我来说是很新的。你知道为什么这样做不符合要求吗?你知道吗


Tags: 函数inselffordatagetdatereturn
1条回答
网友
1楼 · 发布于 2024-05-29 02:29:18

time以及其他可以从外部访问的变量移到def init(self)。请记住,python在运行时创建变量,所以如果您希望变量在任何地方都可以访问,那么应该在类初始化时创建变量。你知道吗

添加: 从代码来看,您应该将temperaturesunlight移动到def init(self)。你知道吗

相关问题 更多 >

    热门问题