简体   繁体   中英

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.

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. The list itself does not have the nome property, only the instances do. You would need to iterate through.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM