简体   繁体   中英

Python class call a method from a class object

How can I fix attribute error in this situation? I have a pandas dataframe where I make some data slicing and transformation and I want to plot the results of the persistence_model function like below.

Edit: I want to customize a function with specific title of the plot, y and x axis and create a horizontal line on the same plot from the results of persitence_model function.


class ResidualErrors():
    def __init__(self, data: pd.Series):
        self.data = data
    def _persistence_forecast_model_nrows(self, test_rows):
        slicer = test_rows + 1
        errors = self.data[-slicer:].diff().dropna()
        return errors
    def _persistence_forecast_model_percrows(self, train_perc):
        n = len(self.data)
        ntrain = int(n * train_perc)
        errors = self.data[ntrain:].diff().dropna()
        return errors
    def persistence_model(self, test_rows=None, train_perc=None):
        if (not test_rows) and (not train_perc):
            raise TypeError(r"Please provide 'test_rows' or 'train_perc' arguments.")
        if test_rows and train_perc:
            raise TypeError(r"Please choose one argument either 'test_rows' or 'train_perc'.")
        if test_rows:
            return self._persistence_forecast_model_nrows(test_rows)
        else:
            return self._persistence_forecast_model_percrows(train_perc)

    @classmethod
    def plot_residuals(obj):
        obj.plot()
        plt.show()

Desired output

res = ResidualErrors(data).persistence_model(test_rows=10)

res.plot_residuals()

>> AttributeError: 'Series' object has no attribute 'plot_residuals'

You need to be more aware of what methods return. The first step creates a ResidualErrors object:

res = ResidualErrors(data)

The second step creates a DataFrame or Series :

obj = res.persistence_model(test_rows=10)

You can call plot_residuals on res but not on obj , as you are currently doing:

res.plot_residuals(obj)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM