I am trying to get familiar with abstract classes, but cannot figure out how I can append to an empty list in the class. this is how the directory i am working in looks like:
my_dir
|__data
| |__colors
| | |__light_colors.csv
| | |__dark_colors.csv
| | |__cold_colors.json
| |__ages
|__code
|__data_reader.py
|__config.py
in my config file i have:
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")
and in my data_reader.py file i have the following code, which is an abstract class.
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')
colors= []
def read_data_type(self):
for files in os.listdir(self.path_to_types):
colors.append(os.path.join(self.path_to_types, files))
g= colorReader()
print(g.read_data_type())
however, it seems the list colors= [] is empty and ideally i would like to use this list in another abstract class so, i can check the extension of the files stored in the list, so this is how the code in data_reader.py continues.
class ExtensionReader(ABC):
@abstractmethod
def file_extension_reader(self): pass
class csvFileExtension(ExtensionReader):
def __init__(self, file_type: PathReader):
self.file_type = file_type
def file_extension_reader(self):
for files in self.file_type:
if files.split(".")[1] == 'csv':
print(files)
but this is where i have no idea how i can make use of the colors =[] list to check the extension of the files that end in .csv
This has nothing to do with abstract classes. You forgot to make your colors
variable an attribute of self
:
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= []
def read_data_type(self):
for files in os.listdir(self.path_to_types):
self.colors.append(os.path.join(self.path_to_types, files))
g= colorReader()
print(g.read_data_type())