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

时间:2016-04-22 00:11:07

标签: python repr

我正在研究一些我创建基本ATM的Python代码。我遇到的问题是我无法得到我想要打印的结果"<'功能Account.balance在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()

1 个答案:

答案 0 :(得分:2)

您将变量和方法命名为同名,因此解释器对使用哪一个感到困惑。更改方法或变量balance的名称,您将不会遇到此问题。另外,这不是java,你不应该无缘无故地使用类。由于您没有使用任何实例变量,因此在该类中包含所有这些方法毫无意义。