Reputation: 9
so for this piece of code, the program has to instantiate the object "acc1" where acc1 = BankAccount(1000)
, where 1000 is the balance. Using the class definition for Bank Account, and using a display method, acc1.display()
, the code should print "balance=1000". My code is printing the balance is part, but not taking into account the 1000 part.
class BankAccount:
def __init__ (self,balance):
self.balance = balance
acc1 = BankAccount("1000")
acc1.display()
print("Balance=",acc1,sep="")
Upvotes: 1
Views: 57
Reputation: 21619
You are trying to print the object itself rather than its balance. You will get the default value printed for the BankAccount
class (something like <__main__.BankAccount object at 0x7f2e4aff3978>
).
There are several ways to resolve the issue:-
First print just the balance property
print("balance=",acc1.balance,sep="")
If you want to modify the class you can define the display
method. This isn't ideal as it limits the way the display information can be used. It has to be displayed to standard out, it cant be joined to other strings etc. It is less flexible.
It would be better to define __str__
and return the display string which can be displayed, concatenate etc.
class BankAccount:
def __init__ (self,balance):
self.balance = balance
def display(self):
print('balance=%s' % self.balance)
def __str__(self):
return 'balance=%s' % self.balance
acc1 = BankAccount("1000")
acc1.display() # use display
print(acc1) # use __str__
Upvotes: 1