Search code examples
pythonclassobjectinitself

What information is __init__.storing?


I read somewhere that __init__ stores information while creating the object. So, let's say I have this code:

class BankAccount(object):
    def __init__(self, deposit):
        self.amount = deposit 

    def withdraw(self, amount):
        self.amount -= amount

    def deposit(self, amount):
        self.amount += amount

    def balance(self):
        return self.amount 

myAccount = BankAccount(16.20)

x = raw_input("What would you like to do?")

if x == "deposit":    
    myAccount.deposit(int(float(raw_input("How much would you like to deposit?"))))
    print "Total balance is: ", myAccount.balance()   
elif x == "withdraw":    
    myAccount.withdraw(int(float(raw_input("How much would you like to withdraw?"))))
    print "Total balance is: ", myAccount.balance()    
else:
    print "Please choose 'withdraw' or 'deposit'. Thank you."

What is __init__ doing or storing. I don't understand what "self.amount" is or how making it = deposit does anything. Is the "self.amount" under __init__ the same as the one under withdraw? I'm just not understanding what "self_amount" does.


Solution

  • Q What is __init__ doing or storing?

    A __init__ gets called whenever you construct an instance of the class. This applies to all classes. It is customary to initialize all your data in this function. In your particular case, you are creating a member data called amount and assigning it to be the same as the deposit argument passed to the function.

    Q I don't understand what "self.amount" is or how making it = deposit does anything.

    A The statement self.amount = deposit accomplishes couple of things. It creates a member data of the class named amount and assigns it to be the value of deposit.

    Q Is the "self.amount" under __init__ the same as the one under withdraw?

    A Yes.

    Q I'm just not understanding what "self.amount" does.

    A It allows you to capture the data of the object. Every class needs to figure out member data it needs to work correctly. In your case, the only data you need is the amount. If you had a class called Employee, it might look something like:

    class Employee(object):
        def __init__(self, firstName, lastName, id, salary):
            self.firstName = firstName 
            self.lastName = lastName 
            self.id = id 
            self.salary = salary