如何在涉及两个类时正确使用__repr__

2024-06-11 22:33:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一些Python代码,在那里我创建了一个基本的ATM。我遇到的问题是,我无法得到我想要的打印“<;”功能的结果账户余额在0x012CBC90>;“而不是实际余额。到目前为止,我只使用jsmith进行了测试。请随时提出任何其他问题,可能会导致以后的问题。你知道吗

class Account:

    def __init__(self,user,pin,balance):
        self.user = user
        self.pin = pin
        self.balance = int(balance)

    def get_user(self):
        return self.user

    def get_pin(self):
        return self.pin

    def balance(self):
        return int(self.balance)

    def setBalance(self,newBalance):
        self.balance = newBalance

    def __repr__(self):
        return str(self.user) + " " + str(self.pin) + " " + str(self.balance)


class ATM:

    def withdraw(self,Person,amount):
        result = Person - amount
        return result


    def check(self,Person):
        Person = Account.balance
        return str(Person)

    def transfer(self,id1,id2):
        pass

    def __str__(self):
        return self



    def main():

    Chase = ATM()

    Database = []

    Teron_Russell = Account("trussell",1738,0)
    Joe_Smith = Account("jsmith",1010,1350)

    print(Teron_Russell)

    Database.append(Teron_Russell)
    Database.append(Joe_Smith)

    print("Welcome to the ATM")
    id  = input("Please enter your user ID: ")
    pin = input("Enter your pin: ")
    chosen = ""

    for i in Database:
        print("Test1")
        name = Account.get_user(i)
        print(name)
        checkPin = Account.get_pin(i)
        print(checkPin)
        if id == name and pin == checkPin:
            chosen = i

    choice = input("What would you like to do. (Type 'Check','Withdraw','Transfer': ")

    if(choice == "Check" or "check"):
        print(Chase.check(chosen))



    # if(choice == "Withdraw" or "withdraw"):
    #     wAmount = eval(input("How much would you like to Withdraw: "))
    #  #   Chase.withdraw(Account.balance,)
    # elif(choice == "Check" or "check"):
    #             Chase.check()
    # else:
    #     print("Invalid Choice!")

if __name__ == "__main__":
    main()

Tags: selfgetreturndefcheckpinaccountdatabase
1条回答
网友
1楼 · 发布于 2024-06-11 22:33:47

您将一个变量和一个方法命名为相同的名称,因此解释器不知道使用哪一个。更改方法或变量的名称balance,就不会有这个问题。另外,这不是java,您不应该无缘无故地使用类。因为您没有使用任何实例变量,所以将所有这些方法都放在该类中是毫无意义的。你知道吗

相关问题 更多 >