【问题标题】:Output shows instance at 0xa19124c as output输出将 0xa19124c 处的实例显示为输出
【发布时间】:2016-12-30 08:35:24
【问题描述】:

朋友。我对 Python 项目的输出有两个疑问。我有两个文件:

银行.py

class clients:
    def __init__(self,name, telephone):
        self.name= name
        self.telephone= telephone

class account:
    def __init__(self, users, number, balance=0):
        self.users= users
        self.number=number
        self.balance=balance

    def resume(self):
        print('Number: %s. balance: %s' %(self.users, self.balance))

和 BankClients.py:

from Bank import clients
from Bank import account

client1= clients('john', '555-0804')
account1= account([client1], 1, 3000)

account1.resume()

问题,输出显示:

Number: [<Bank.clients instance at 0xa19124c>]. balance: 3000

什么时候应该:

Number: 1. balance:3000

我在其他电脑上运行过,问题也是一样的。我尝试在 print(xxx) 行中写入 bank.py 文件

print('number ... balance...'%(self.balance, self.balance)) 

输出是相同的,只是在 self.balance 输出实例中添加了另一个代码。

提前感谢您的帮助。

【问题讨论】:

  • 改成print('Number: %s. balance: %s' %(self.number, self.balance))就行了。
  • 谢谢吉姆!但不幸的是,同样的问题,

标签: python-3.x object instance


【解决方案1】:

您可以通过实现自己的__str____repr__ 函数来决定str(account1)(或repr(account1) [这是python 在打印list 事物时使用的内容] 的输出应该是什么样子。

例如:要自定义str(client),您可以这样做:

class clients:
    def __init__(self,name, telephone):
        self.name= name
        self.telephone= telephone

    def __str__(self):
        return 'clients(name={}, telephone={})'.format(self.name,
                                                       self.telephone)

(并为__repr__ 添加类似的内容)。

【讨论】:

    猜你喜欢
    • 2018-05-21
    • 1970-01-01
    • 2011-12-17
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多