创建一个名为 Investment 的 class,其字段名为 principal 和 interest rate

Creat a class called Investment with fields named principal and interest rate

我有以下问题。 编写一个名为 Investment 的 class,其中包含名为 principal 和 interest 的字段。构造函数应该设置这些字段的值。应该有一个名为 value_after 的方法 returns n年后的投资价值。这个公式是p(1 + i)n,其中p是本金,i是利率。

我已经创建了 class 和那些要求的方法。

class Investment:
    def __init__(self,principal,interest_rate):
        self.principal=principal
        self.interest_rate=interest_rate
    def value_after(self):
        n=int(input('Number of years\n'))
        return self.principal(1+self.interest_rate)**n    

final_result=Investment(float(input('Digit principal\n')),float(input('Digit interest rate\n')))
print('Final result is',final_result.value_after)

我希望打印 value_after 函数中给出的最终结果,但是当我 运行 程序时,它会收到以下警告: 最后的结果是<bound method Investment.value_after of <__main__.Investment object at 0x7f0760110850>>

在return 语句中的变量self.principal 后面使用() 调用函数并添加一个运算符(我添加了一个* 运算符)。这将修复错误:

class Investment:

    def __init__(self,principal,interest_rate):
        self.principal=principal
        self.interest_rate=interest_rate
    def value_after(self):
        n=int(input('Number of years\n'))
        return self.principal*(1+self.interest_rate)**n    

final_result=Investment(float(input('Digit principal\n')),float(input('Digit interest rate\n')))

print('Final result is',final_result.value_after())

首先,你有一个缩进问题,def value_after(self): 之后的两行必须相对于它缩进:value_after has no body at all with your indentation.

PS:我看到你更正了:-)