0

I am trying to define a set of functions outside of a class that I want to use. Then however I want to make these functions available as methods inside the class. Simple example:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import pylab

def my_plot(self):
    plt.clf()
    fig, ax = plt.subplots()
    ax.plot(self.timeline, self.sample, color = self.color)
    plt.show()

class test(object):
    def __init__(self, color = 'black'):
        self.sample = np.random.normal(0, 1, 100)
        self.timeline = np.arange(1,101,1)
        self.color = color
        self.plot = my_plot

Now when I call,

my_test = test()
my_test.plot()

I get the error:

my_plot() missing 1 required positional argument: 'self'

However,

my_test.plot(my_test)

produces the expected result.

According to what I understand, my_test.plot() is equivalent to plot(my_test) so I do not understand why I should write my_test.plot(my_test) here.

Any help would be greatly appreciated.

Affaeng
  • 115
  • 6
  • More specifically this answer: https://stackoverflow.com/a/39984352/4720935 – Mel Oct 23 '17 at 09:08
  • thanks. Before I couldn't deduce from that question what I was doing wrong, but after inspecting it more carefully, I found what I needed. – Affaeng Oct 23 '17 at 09:54

0 Answers0