Python中的OOP。我该怎么做类方法?

时间:2018-11-13 04:11:18

标签: python oop

我正在尝试制作一个程序(针对家庭作业问题),该程序使用不同的帐户,并允许您进行存款/提款。当Account.totalAllBalance提示时,我还应该显示所有帐户的余额。一切都很好,但是我试图找出如何将起始余额添加到我的totalAllBalance总计中。我不断收到此错误,我不确定为什么。我是编程新手,应该使用课堂上做的非常基本的编程。我的问题是为什么我会收到此错误以及如何解决?

错误在第20行,提示

初始化中     Account.totalAllBalance = Account.totalAllBalance +数值 TypeError:+不支持的操作数类型:“方法”和“整数”

这是我到目前为止的尝试:

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).")

1 个答案:

答案 0 :(得分:0)

原因是因为您同时拥有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)