[英]How to Print my Object name in Python
So I have a problem with this code: 所以我有这个代码的问题:
class Cliente:
def __init__(self,nome,telefone):
self.nome = nome;
self.telefone = telefone;
class Conta:
def __init__(self,clientes,numero,saldo=0):
self.saldo = saldo
self.numero = numero
self.clientes = clientes
def resumo(self):
print('Cliente: {0:s} CC Numero: {1:s} Saldo: {2:10.2f}'.format(self.clientes.nome, self.numero, self.saldo))
def saque(self,valor):
if self.saldo >= valor:
self.saldo -= valor
def deposito(self,valor):
self.saldo += valor
When I go to test my class: 当我去上课时:
from tatu import Cliente
from tatu import Conta
joao = Cliente('Joao da Silva','666-6666')
maria = Cliente('Maria da Penha','234-5678')
conta1 = Conta(joao,'0138',1500)
conta1.deposito(800)
conta1.saque(1300)
conta2 = Conta([joao,maria],'0139',1000)
conta2.deposito(1000)
conta1.resumo()
conta2.resumo()
My second account don't print and I have this error: 我的第二个帐户无法打印,并且出现此错误:
print('Cliente: {0:s} CC Numero: {1:s} Saldo: {2:10.2f}'.format(self.clientes.nome, self.numero, self.saldo))
AttributeError: 'list' object has no attribute 'nome'
You are mixing types; 您正在混合类型; sometimes your
clientes
is one Cliente
instance, sometimes it is a list. 有时你的
clientes
是一个 Cliente
例如,有时它是一个列表。
Always make it a list instead, and then loop over that list: 始终将其制成列表,然后遍历该列表:
# account with just one client
conta1 = Conta([joao],'0138',1500)
# account with two clients
conta2 = Conta([joao,maria],'0139',1000)
and now that it is always a list, use a loop: 现在它始终是列表,请使用循环:
def resumo(self):
for client in self.clientes:
print('Cliente: {0:s} CC Numero: {1:s} Saldo: {2:10.2f}'.format(client.nome, self.numero, self.saldo))
or perhaps split out the client names list and print account number and saldo separately: 或分开列出客户名称列表,并分别打印帐号和密码:
def resumo(self):
for client in self.clientes:
print('Cliente: {0:s}'.format(client.nome))
print('CC Numero: {1:s} Saldo: {2:10.2f}'.format(self.numero, self.saldo))
self.clientes
is not an instance of Cliente, it is a list of instances. self.clientes
不是self.clientes
的实例,它是实例的列表。 The list itself does not have the nome property, only the instances do. 列表本身不具有nome属性,只有实例具有。 You would need to iterate through.
您将需要遍历。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.