【问题标题】:How to use classes to call for an object using a variable?如何使用类通过变量调用对象?
【发布时间】:2019-09-18 11:52:40
【问题描述】:

我正在尝试通过在 Python 上使用面向对象编程来解决“保持变化”问题。我做了一个类:

class BankAccount:

    def __init__(self):
        self.savings = 100

    def savings (self, amount):
        self.savings = self.savings + amount
        return self.savings

    def getSavings (self):
        return self.savings

然后我制作了一个单独的文件,尝试从文件中取出数字,四舍五入,然后将差额存入储蓄账户。但是,当我调用储蓄并尝试使用变量来增加储蓄时,我不断收到一条错误消息,指出它需要是 int

def main():

    account1 = BankAccount()

    file1 = open("data.txt","r")
    s = 0       # to keep track of the new savings
    for n in file1:
        n = float(n)    #lets python know that the values are floats
        z= math.ceil(n)         #rounds up to the whole digit
        amount = float(z-n)
        s = int(amount + s)
        x = (account1.savings(s))  # <<this is where the error occurs

【问题讨论】:

    标签: python class object object-oriented-database onlinebanking


    【解决方案1】:

    您的类有一个名为savings 的属性,如__init__ 中定义的那样,还有一个同名的方法(函数)。当您引用它时,解释器将不知道您是要调用该方法还是获取该属性。

    将方法名称从 savings 更改为其他名称,例如 make_savings

    def make_savings(self, amount):
    

    而不是

    def savings(self, amount):
    

    应该有效

    【讨论】:

    • 感谢您的帮助!
    • 循环没有遍历我的外部文本文件中的所有值。它只计算最后一个值。可能是什么问题?我的外部文本文件是这样的:10.90 13.59 12.99
    猜你喜欢
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    相关资源
    最近更新 更多