Установка объекта в качестве значения для другого атрибута объекта вызывает «AttributeError: не может установить атрибут» - PullRequest
0 голосов
/ 24 апреля 2020

Я пытаюсь передать содержимое CSV-файла в DataFrame Panda в Python.

Я использую архитектуру слоя, где основной вызывает UseCase. Этот UseCase вызывает репозиторий, который получает данные типа Panda DataFrame из файла CSV и устанавливает их в атрибут класса DataAsDataFrame. Этот set завершается неудачно и возвращает:

AttributeError: невозможно установить атрибут

Вот код:

main.py

    ifile = "data/file.csv"

    data_uc = DataAsDataFrameGetUC(
         vars_list_repo=DataAsDataFrameGetRepository,
         input_path=ifile
     )
    data_uc.execute()

DataAsDataFrameGetU C

class DataAsDataFrameGetUC(UseCaseInterface):
    """ DataAsDataFrameGetUC class retrieves the data as a Panda DataFrame """

    def __init__(self,
                 vars_list_repo: DataRepositoryInterface,
                 input_path: str):
        """ Constructor for the DataAsDataFrameGetUC class """
        self._repository = vars_list_repo
        self._input_path = input_path

    def execute(self):
        """ The execute() method calls the adapter to get the data as a Panda DataFrame """
        return self._repository.find(self._input_path)

DataRepositoryInterface

class DataRepositoryInterface(metaclass=abc.ABCMeta):

    @staticmethod
    @abc.abstractmethod
    def find(input_path: str) -> DataInterface:
        pass

DataAsDataFrameGetRepository

class DataAsDataFrameGetRepository(DataRepositoryInterface):

    @staticmethod
    def find(input_path: str) -> DataInterface:
        data_df = DataAsDataFrame()

        # Reading only the columns name
        col_names = pd.read_csv(input_path, skiprows=2, nrows=0).columns
        # Defining the three last columns as int
        types_dict = {'C': int, 'D': int, 'E': int}
        # The rest of the columns (aka the first and the second) will be strings
        types_dict.update({col: str for col in col_names if col not in types_dict})
        # Reading the rows from the CSV
        df = pd.read_csv(input_path, skiprows=2, header=0, dtype=types_dict)

        data_df.data = df

        return data_df

DataAsDataFrame

class DataAsDataFrame(DataInterface):
    """ InputDataFrame class specifies Security Exchange attributes and methods """

    def __init__(
            self,
            data: Optional[DataFrame] = None
    ):
        """ Constructor for the InputDataFrame class """
        self._data = data

    @property
    def data(self) -> DataFrame:
        return self._data

    @property
    @data.setter
    def data(self, data):
        """ Setter for the data attribute """
        self._data = data

    @classmethod
    def factory(
            cls,
            data: Optional[DataFrame] = None
    ) -> DataInterface:

        return cls(
            data=DataFrame()
        )

DataInterface

class DataInterface(metaclass=abc.ABCMeta):
    """
        Interface to be implemented by class storing the Data from the Input
   """

    @property
    @abc.abstractmethod
    def data(self):
        pass

Спасибо

Редактировать: Может ли проблема быть связана с этими данными: Необязательно [DataFrame] = Нет Из того, что я понимаю, это позволяет определить данные аргумента как необязательные, говоря, что этот параметр имеет Тип DataFrame (который является изменяемым).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...