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

How to properly use __repr__ when two classes are involved

我正在编写一些 Python 代码来创建基本的 ATM。我遇到的问题是我无法获得我想要打印的结果“<'function Account.balance at 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()

您将一个变量和一个方法命名为相同的名称,因此解释器不知道该使用哪个。更改方法或变量的名称 balance,您将不会遇到此问题。此外,这不是 java,您不应无缘无故地使用 classes。由于您没有使用任何实例变量,因此在 class.

中包含所有这些方法毫无意义