python - Python 中的 OOP。我如何做类方法?
问题描述
我正在尝试做一个程序(针对家庭作业问题),它可以创建不同的帐户并允许您从中存款/取款。当使用 Account.totalAllBalance 提示时,我还应该显示所有帐户的余额。一切都很顺利,但我想弄清楚如何将起始余额添加到我的 totalAllBalance 总数中。我不断收到这个错误,我不知道为什么。我对编程很陌生,我应该使用我们在课堂上做的非常基本的编程。我的问题是为什么我会收到这个错误,我该如何解决?
错误在第 20 行,它说
在init Account.totalAllBalance = Account.totalAllBalance + num TypeError: +: 'method' 和 'int' 不支持的操作数类型
这是我迄今为止的尝试:
class Account:
totalAllBalance = 0
totalAccounts = 0
def __init__(self, name, startBalance):
self.name = name
self.startBalance = startBalance
num = startBalance
if self.startBalance < .01:
print("You may not start an account with that balance.")
else :
self.deposits = 0
self.withdraws = 0
Account.totalAccounts += 1
if Account.totalAccounts is 1:
Account.totalBalance = 0
else:
Account.totalAllBalance = Account.totalAllBalance + num
def deposit(self, num):
self.deposits += num
print(self.name, "has deposited", num, "dollars.")
Account.totalAllBalance = Account.totalAllBalance + num
return(self.totalBalance())
def withdraw(self, num):
self.withdraws += num
if num > self.startBalance + -1*(self.withdraws-num) + self.deposits:
print("You may not withdraw more than your balance.")
self.withdraws -= num
else:
num2= -1 * num
print(self.name, "has withdrawn", num,"dollars.")
return(self.totalBalance())
Account.totalAllBalance = Account.totalAllBalance + num2
def totalBalance(self):
if self.withdraws is None:
W = 0
if self.deposits is None:
D = 0
S = self.startBalance
W = self.withdraws * -1
D = self.deposits
num = S + W + D
print(self.name,"has", S + W + D , "dollars in their account.")
@classmethod
def totalAllBalance(cls):
print(cls.totalAllBalance)
@classmethod
def amtAccounts(cls):
print("There is", cls.totalAccounts, "account(s).")
解决方案
原因是因为您totalAllBalance
同时拥有类方法和类属性。除此之外,您访问的方式Account.totalAllBalance
使编译器解释为方法而不是属性。我建议改为使用self.totalAllBalance
并为您的类方法使用不同的名称(例如printTotalAllBalance
)
def deposit(self, num):
self.deposits += num
print(self.name, "has deposited", num, "dollars.")
self.totalAllBalance = self.totalAllBalance + num
return(self.totalBalance())
@classmethod
def printTotalAllBalance(cls):
print(cls.totalAllBalance)
推荐阅读
- c++ - I can't print 2D vector
- angular - Invoke modal inside SwitchMap in angular2 resolver
- esp8266 - 如何发送和接收长数据 HC-05
- javascript - 部署 express 并使用路由前缀做出反应
- r - 我的 R 代码有什么问题,它没有给出预期的输出
- tensorflow - MultiWorkerMirroredStrategy() not working on Google AI-Platform (CMLE)
- python - 我在将我的机器人文件推送到 heroku 时遇到问题
- laravel - How to add a new Column to an exesting Table in OctoberCms DB
- php - 如何使用 url 显示数据
- c# - It's possible to convert event triggers to viewmodel using converters?