首页 > 解决方案 > python方法:append在抽象类的子类中返回一个空列表

问题描述

我正在尝试熟悉抽象类,但无法弄清楚如何附加到类中的空列表。这就是我正在工作的目录的样子:

 my_dir
  |__data
  |    |__colors
  |    |    |__light_colors.csv
  |    |    |__dark_colors.csv
  |    |    |__cold_colors.json
  |    |__ages
  |__code
       |__data_reader.py
       |__config.py

在我的配置文件中,我有:

import os

REPO_ROOT_DIRECTORY = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
colors_DATA_DIRECTORY = os.path.join(REPO_ROOT_DIRECTORY, "data")

在我的 data_reader.py 文件中,我有以下代码,这是一个抽象类。

from abc import ABC, abstractmethod
from config import colors_DATA_DIRECTORY
import os

class PathReader(ABC):

    @abstractmethod
    def read_data_type(self): pass
    
class colorReader(PathReader):
    def __init__(self):
        self.path_to_types = os.path.join(colors_DATA_DIRECTORY, 'colors')
        self.colors= []
        # print(self.colors)-->empty

    def read_data_type(self):
        for files in os.listdir(self.path_to_types):
            all_colors = os.path.join(self.path_to_types, files)
            self.colors.append(all_colors)
            # print(all_colors) --> prints the .csv and .json files and their path
            # print(files) --> prints the .csv and .json files

 g= colorReader()
 print(g.read_data_type())

我不确定该方法的哪一部分是错误的,因此附加不起作用。我试图打印出 for 循环中的元素,一切似乎都很好,但是当我打印 self.colors 列表时,它是空的。

标签: python-3.xlistappendabstract-methods

解决方案


推荐阅读