Skip to content Skip to sidebar Skip to footer

Instantiating Object And Using Class Definition __init__

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,

Solution 1:

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.

classBankAccount:def__init__(self,balance):
        self.balance = balance
    defdisplay(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__

Post a Comment for "Instantiating Object And Using Class Definition __init__"