ya23
ya23

Reputation: 53

Missing 2 required positional arguments - Classmethod Python

Sorry, I'm struggling at this for quite some time. I'm trying to use function totalPayments which uses the monthlyPayment class function with parameters pass through in the initialisation phase. I'm getting an error missing 2 required positional arguments

class Loan(object):
   def __init__(self, asset, face, rate , term):
       self._asset = asset
       self._face = face
       self._rate = rate
       self._term = term

   @classmethod
   def monthlyPayment(cls,face,rate,term,period=None):
       return ((rate*face*((1+rate)**term)))/(((1+rate)**term)-1)

   def totalPayments(self):
       return (self.monthlyPayment(self) * self._term) 

l = Loan(None,1000,0.025,10)
print(l.totalPayments()) # gets an error missing 2 required positional arguments

edit: Thank you very much for the hekp and I should be amending my def monthlyPayment function to take in the arguments

Upvotes: 1

Views: 20834

Answers (2)

Chris Doyle
Chris Doyle

Reputation: 12002

The stack error you get is:

Traceback (most recent call last):
  File "C:/Users/cd00119621/PycharmProjects/ideas/stackoverflow.py", line 16, in <module>
    print(l.totalPayments())
  File "C:/Users/cd00119621/PycharmProjects/ideas/stackoverflow.py", line 13, in totalPayments
    return (self.monthlyPayment(self) * self._term)
TypeError: monthlyPayment() missing 2 required positional arguments: 'rate' and 'term'

The clue here is that its the monthlyPayment() method thats giving the error missing 2 args. this method expects 3 args passed to it (excluding self) and the 4th is optional.

def monthlyPayment(cls,face,rate,term,period=None):

but when you call this from your totalPayments method you only pass one argument which is self.

return (self.monthlyPayment(self) * self._term)

you dont need to pass self, it will be passed automatically, so you need to pass the other 3 expected params face,rate,term

Upvotes: 1

L3viathan
L3viathan

Reputation: 27283

You are calling monthlyPayment from the instance (self), and you're not providing arguments for face, rate, and term.

It also shouldn't be a classmethod, since you use attributes of the instance:

class Loan(object):
   def __init__(self, asset, face, rate , term):
       self._asset = asset
       self._face = face
       self._rate = rate
       self._term = term

   def monthlyPayment(self, period=None):
       return ((self._rate*self._face*((1+self._rate)**self._term)))/(((1+self._rate)**self._term)-1)

   def totalPayments(self):
       return (self.monthlyPayment() * self._term)

Upvotes: 3

Related Questions