【问题标题】:Errors in minor details in a class output类输出中的次要细节错误
【发布时间】:2013-11-30 00:36:22
【问题描述】:

我有两个文件:

class Account:
def __init__(self,id=0,balance=100.0,AIR=0.0):
    self.__id = id
    self.__balance = balance
    self.__AIR = AIR
def getd(self):
    return self.__id
def getbalance(self):
    return self.__balance
def getAnnualInterest(self):
    return self.__AIR
def setid(self,newid):
    self.__id = newid
def setbalance(self,newbalance):
    self.__balance = newbalance
def setAnnualInterestRate(self,newrate):
    self.__AIR = newrate
def getMonthlyInterestRate(self):
    return self.__AIR/12
def getMonthlyInterest(self):
    return self.__balance*self.getMonthlyInterestRate()

def withdraw(self,amount):
    if amount<=self.__balance:
        self.__balance -= amount
def deposit(self,amount):
    self.__balance += amount
def __str__(self):
    return "Account ID : {0.setid} Account Balance : {0.setbalance} Annual Interest Rate : {0.setAnnualInterestRate}".format(self)

和测试:

   from Account import Account
def main():
    accountA = Account(0,100,0)
    accountA.setid = 1234
    accountA.setbalance = 20500
    accountA.setAnnualInterestRate = 0.375
    print(accountA)
    accountA.withdraw(500)
    accountA.deposit(1500)
    print(accountA)
    print(accountA.getMonthlyInterest())
main()

我的输出大部分是正确的,但有两个小细节我弄错了,我不确定问题出在代码的哪里。

账户 ID:1234 账户余额:20500 年利率:0.375 账户 ID:1234 账户余额:20500(这应该是 21500) 年利率:0.375 0.0(这应该是 671.875 但不知何故我弄错了)

【问题讨论】:

  • self.__balance 不会随着存款和取款的调用而改变。我自己是 python 新手,所以我不确定类中的变量,但这似乎是问题所在。
  • 为什么你的字符串格式调用setter方法(setid,setbalance...)
  • self.getbalance() 产生正确的结果。

标签: python class account


【解决方案1】:

accountA.setbalance = 20500 不调用setbalance 方法。它更改 setbalance 属性的值 20500(也就是说,在这一行之后,accountA.setbalance 不再是一个方法,而是一个 int)。相反,你想要accountA.setbalance(20500)

但是,首先,您所做的完全不是 Python 的(您是 Java/C#/C++ 程序员,不是吗?)。 Getter 和 setter 是 Python 中的反模式:只需访问和更改 idbalance 等。属性,并在设置/访问它们时(并且如果)需要执行计算/检查时将它们设为属性。

另外,__attribute 不是 Python 中的私有属性。将属性标记为“私有”的 Pythonic 方式是 single 前导下划线。然而,这只是一个约定,属性本身仍然是公开的(一切都在 Python 中——它没有可见性修饰符的概念)。

【讨论】:

  • 我主要涉足 C++。对python不太熟悉。
【解决方案2】:

这个:

accountA.setid = 1234
accountA.setbalance = 20500
accountA.setAnnualInterestRate = 0.375

不调用函数。您实际上以这种方式将函数更改为变量。要调用函数,请使用以下符号:

accountA.setid(1234)
accountA.setbalance(20500)
accountA.setAnnualInterestRate(0.375)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 2019-03-31
    • 2016-07-12
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多