user4188052
user4188052

Reputation:

Method is printing something that I am not expecting

class Bank:
    def __init__(self, name, id, balance): 
        self.name = name
        self.id = id
        self.balance = balance
    def print_out(self):
          return self.name, self.id, self.balance
x = Bank("Kyle", 12345, 500)
print x.print_out()

I am getting ("Kyle", 12345, 500) as my output, but I was expecting Kyle 12345 500.

Upvotes: 0

Views: 50

Answers (2)

muthan
muthan

Reputation: 2472

Besides writing an extra function, a class has an builtin represent attribute __repr__ that you can modify. Every time you call in your case print x you get the return value of __repr__.

The standard value of __repr__ is some hash. To modify __repr__ you can do something the following:

class Bank:
    def __init__(self, name, id, balance): 
        self.name = name
        self.id = id
        self.balance = balance
    def __repr__(self):
        return "%s %d %d" % (self.name, self.id, self.balance)

So when you do the following

x = Bank("Kyle", 12345, 500)
print x

you get the output Kyle 12345 500 as representation for you object

Upvotes: 1

f.rodrigues
f.rodrigues

Reputation: 3587

return with mutiple objects returns a tuple, hence the (), and the objects are represented as they are, strings with "".

In order to have a single line with all the arguments you need to string manipulate.

try something like

print "%s %d %d" % x.print_out()

EDIT:

You can change the return condition to:

def print_out(self):
    return "%s %d %d" % (self.name, self.id, self.balance)

Upvotes: 1

Related Questions