Py学习  »  Python

缺少2个必需的位置参数-Classmethod Python

Zy23 • 4 年前 • 240 次点击  

对不起,我在这件事上挣扎了很长时间。我正在尝试使用totalPayments函数,它使用monthlyPayment类函数,在初始化阶段传递参数。我得到一个错误缺少2个必需的位置参数

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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51240
 
240 次点击  
文章 [ 2 ]  |  最新文章 4 年前
L3viathan Chris Doyle
Reply   •   1 楼
L3viathan Chris Doyle    4 年前

得到的堆栈错误是:

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'

这里的线索是 monthlyPayment() 方法,该方法提供缺少2个参数的错误。此方法需要传递3个参数(不包括self),第4个参数是可选的。

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

但是当你从你的 totalPayments 方法只传递一个自变量。

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

你不需要传递self,它会自动传递,所以你需要传递其他3个期望的参数 face,rate,term

L3viathan Chris Doyle
Reply   •   2 楼
L3viathan Chris Doyle    4 年前

你在打电话 monthlyPayment 从实例( self ),并且您没有为 face , rate ,和 term .

它也不应该是classmethod,因为您使用实例的属性:

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)