【问题标题】:python class AttributeErrorpython类属性错误
【发布时间】:2020-06-04 08:16:19
【问题描述】:

这个脚本的目的是:

• 读取一组 csv 文件。

• 刮掉日期并从中提取一些特征。

• 将这些 csv 文件合并到一个数据框中。

• 将最终数据框导入另一个类并打印。

代码如下:

import pandas as pd
import os


class DataSource:
    def __init__(self):
        self.dfs = []
        self.final = pd.DataFrame()
        self.names = ['Date', 'Time', 'open', 'high', 'low', 'close', 'Volume']
        self.directory = os.chdir(r"C:\Users\Sayed\Desktop\forex")

    def merge(self):
        for file in os.listdir(self.directory):
            df = pd.read_csv(file, names=self.names,
                             parse_dates={'Release Date': ['Date', 'Time']})
            self.dfs.append(df)

        self.final = pd.concat(self.dfs, axis=0)
        self.final = self.final[['Release Date', 'open', 'high', 'low', 'close']]
        print(self.final.head())
        return self.final


class test():
    def __init__(self):
        self.df = DataSource.final

    def print(self):
        return print(self.df.head())

x = test()
x.print()

这是错误:

Traceback(最近一次通话最后一次):

文件“C:/Users/Sayed/PycharmProjects/project/hello.py”,第 31 行,在 x = 测试()

init 中的文件“C:/Users/Sayed/PycharmProjects/project/hello.py”,第 26 行 self.df = DataSource.final

AttributeError: type object 'DataSource' has no attribute 'final'

【问题讨论】:

  • 是的,final 是一个实例属性,而不是类属性。 DataSource().final 例如可以工作……
  • 您尚未初始化数据源实例。 final 属于一个实例,而不是类。 (它在init 内)因此,如果不初始化Datasource 的实例,就无法访​​问final。也就是说,我不知道你想用test 类实现什么。

标签: python oop


【解决方案1】:

您无法直接在 DataSource 类中访问 self.final 属性。您需要先实例化它。所以你的test 类会更像:

class test():
    def __init__(self):
        self.d = DataSource()
        self.df = self.d.merge()
    def print(self):
        return print(self.df.head())

【讨论】:

    猜你喜欢
    • 2018-02-27
    • 2017-07-17
    • 1970-01-01
    • 2014-03-21
    • 2013-07-01
    • 2011-10-12
    • 1970-01-01
    • 2016-04-19
    • 2010-12-23
    相关资源
    最近更新 更多