Search code examples
pythontypeerrorstatic-methods

When overloading a method: "TypeError: Missing 1 required positional argument"


I am writing some code to fit distributions to data and since for the Pareto 1 distribution, theta was fixed, I wrote the following code:

class ParetoI:
    alpha = None
    theta = None

    def __init__(self, alpha, theta=.5):
        self.alpha = alpha
        self.theta = theta
        return

    def pdf(self, x):
        return ParetoI.pdf(self.alpha, x, self.theta)

    # Some other code

    @staticmethod
    def pdf(alpha, x, theta=.5):
        return alpha * theta ** alpha / x ** (alpha + 1)

Then in my main routine, after I have fit a distribution to the given sample data, I try to plot the density:

# par1 = ParetoI(some_args)
x_range = np.linspace(.5, 80, 200)
plt.plot(x_range, par1.pdf(x_range), label='Pareto I')

But I get the following error:

TypeError: pdf() missing 1 required positional argument: 'x'

I assume that this is somehow because I call the generalized, static function from the par1.pdf. How can I fix this code? Am I simply not allowed to have a static function with the same name as a class method? I guess this is easily fixable by simply removing the static functions, but I thought it might be handy to be able to use these distributions without instantiating an object for further use. Is this bad design?


Solution

  • So, as suggested above, the Python way to write that is:

    def pdf(alpha, x, theta=.5):
        return alpha * theta ** alpha / x ** (alpha + 1)
    
    class ParetoI:
        alpha = None
        theta = None
    
        def __init__(self, alpha, theta=.5):
            self.alpha = alpha
            self.theta = theta
            return
    
        def pdf(self, x):
            return pdf(self.alpha, x, self.theta)