【问题标题】:TypeError: unbound method amount () must be called with loan instance as first argument (got nothing instead)TypeError: unbound method amount () must be called with loan instance 作为第一个参数(什么都没有)
【发布时间】:2018-01-20 08:44:08
【问题描述】:
import datetime


class Loan:
    def __init__(self, principal, rate, date):
        self.p=principal
        self.r=rate
        self.d=date

    def amount(self):
        interest=self.r*self.p
        now=datetime.date.today()
        delta=datetime.timedelta(1)
        then=self.d
        while then <= now:
            print then.strftime("%Y-%m-%d")
            print outstanding 
            outstanding +=interest
            then+=delta


x=Loan
x.p=10000
x.r=0.1/7
x.d=datetime.date.today()-
    datetime.timedelta(5)
x.amount()

我希望获得每个间隔的日期和未结金额,但我收到一个错误,我检查了过去的解决方案并与我的代码进行了交叉检查,以确保在实例上调用了该方法。运行代码时出现的错误是:

TypeError: unbound method amount () must be called with loan instance 作为第一个参数(什么都没有)

【问题讨论】:

  • 您需要先将Loan 类实例化为一个对象(使用括号Loan()),然后再对其方法进行操作,尝试p=10000 r=0.1/7 d=datetime.date.today() - datetime.timedelta(5) x=Loan(p,r,d)
  • x=Loan() 完美解决。谢谢。 x=Loan(p,r,d) 给出错误“构造函数不接受参数”。所以一次实例化每个参数可以解决它。

标签: python-2.7


【解决方案1】:
import datetime


class Loan:
    def __init__(self, principal = 0, rate = 0, date = 0):
        self.p=principal
        self.r=rate
        self.d=date

    def amount(self):
        interest=self.r*self.p
        now=datetime.date.today()
        delta=datetime.timedelta(1)
        then=self.d
        outstanding = 0
        while then <= now:
            print then.strftime("%Y-%m-%d")
            print outstanding 
            outstanding +=interest
            then+=delta


x= Loan()
x.p=10000
x.r=0.1/7
x.d=datetime.date.today()-datetime.timedelta(5)
x.amount()

为构造函数参数赋予默认值。

【讨论】:

    猜你喜欢
    • 2015-02-10
    • 2019-10-30
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 2018-03-31
    • 2014-03-08
    • 1970-01-01
    • 2021-06-04
    相关资源
    最近更新 更多