【问题标题】:__str__(self) function not working for printing objects in Python__str__(self) 函数不适用于在 Python 中打印对象
【发布时间】:2019-11-16 21:06:37
【问题描述】:

我一直致力于改进在 Python 中使用类和对象,但在我的程序中显示不同对象的值时遇到了麻烦。我的导师告诉我,只要将对象传递给 print() 函数,就会自动调用 str(self) 函数,但是,输出仍然显示对象在内存中的地址,而不是价值。我在下面记录了我的代码在两个不同的编译程序中运行它,但仍然找不到我的错误发生的位置。

# the class of the bank account
class BankAccount:
    def __init__(self, bal):
        self.__balance = bal

# deposits the amount given by the user
def deposit(self, amount):
    self.__balance += amount

# withdraws the amount given by the user
def withdraw(self, amount):
    if(self.__balance >= amount):
        self.__balance -= amount
    else:
        print("Error: Insufficient funds")

# returns the current balance of the user's account
def get_balance(self):
    return self.__balance

# sets the user's account given a specified balance
def set_balance(self, bal):
    self.__balance = bal

# prints the user's balance
def __str__(self):
    return "The balance is $" + format(self.__balance, ",.2f")

def main():
    start_bal = float(input("Enter your starting balance: ")) # retrieves balance from the user
    savings = BankAccount(start_bal) # creates an object that hold's the user's balance
    print(savings)

main()

程序输出<__main__.BankAccount object at 0x0000025EE6535A90>而不是获取帐户的值

请让我知道我可以更改以纠正问题的任何内容。谢谢。

【问题讨论】:

  • 你的格式有问题,需要缩进defs
  • 这些函数不在类中,只有__init__在你的类中,你应该正确格式化你的代码
  • 谢谢大家都是正确的!但是,我有一个问题。你知道为什么函数需要在类中缩进吗?为什么程序中已经声明了它们,我却无法正确使用它们?

标签: python string class object printing


【解决方案1】:

这是一个缩进问题,你的类只定义为:

# the class of the bank account
class BankAccount:
    def __init__(self, bal):
        self.__balance = bal

尝试将本节下方的所有代码缩进一个缩进块,直到到达 def main() 函数,这样 BankAccount 就会获得您想要的方法:

# the class of the bank account
class BankAccount:
    def __init__(self, bal):
        self.__balance = bal

    # deposits the amount given by the user
    def deposit(self, amount):
        self.__balance += amount

    # withdraws the amount given by the user
    def withdraw(self, amount):
        if(self.__balance >= amount):
            self.__balance -= amount
        else:
            print("Error: Insufficient funds")

    # returns the current balance of the user's account
    def get_balance(self):
        return self.__balance

    # sets the user's account given a specified balance
    def set_balance(self, bal):
        self.__balance = bal

    # prints the user's balance
    def __str__(self):
        return "The balance is $" + format(self.__balance, ",.2f")

def main():
    start_bal = float(input("Enter your starting balance: ")) # retrieves balance from the user
    savings = BankAccount(start_bal) # creates an object that hold's the user's balance
    print(savings)

main()

【讨论】:

    【解决方案2】:

    当 main 被调用并在 print(savings) 被执行时,它会打印 BankAccount 类的 str 表示,这是储蓄内存地址,然后因为你的 str 实现是在类之外定义的它与类无关。

    试试这个:

    # the class of the bank account
    class BankAccount:
        def __init__(self, bal):
            self.__balance = bal
    
        # deposits the amount given by the user
        def deposit(self, amount):
            self.__balance += amount
    
        # withdraws the amount given by the user
        def withdraw(self, amount):
            if(self.__balance >= amount):
                self.__balance -= amount
            else:
                print("Error: Insufficient funds")
    
        # returns the current balance of the user's account
        def get_balance(self):
            return self.__balance
    
        # sets the user's account given a specified balance
        def set_balance(self, bal):
            self.__balance = bal
    
        # prints the user's balance
        def __str__(self):
            return "The balance is $" + format(self.__balance, ",.2f")
    
    def main():
        start_bal = float(input("Enter your starting balance: ")) # retrieves balance from the user
        savings = BankAccount(start_bal) # creates an object that hold's the user's balance
        print(savings)
    
    main()
    

    【讨论】:

      【解决方案3】:

      您需要覆盖 BankAccount 类的 __str__ 运算符:

      class BankAccount:
          def __init__(self, bal):
              self.__balance = bal
      
          def __str__(self):
              return "The balance is $" + format(self.__balance, ",.2f")
      
      
      In [25]: start_bal = 2.3
      In [27]: savings = BankAccount(start_bal) 
      
      In [28]: print(savings)
      The balance is $2.30
      

      只需将你的方法正确地嵌套在你的类中

      【讨论】:

        猜你喜欢
        • 2012-11-15
        • 2011-04-03
        • 2023-03-23
        • 2011-02-07
        • 2022-11-30
        • 1970-01-01
        • 2021-09-05
        • 1970-01-01
        • 2011-05-14
        相关资源
        最近更新 更多