python - What information is __init__.storing? -
i read somewhere __init__ stores information while creating object. so, let's have 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 do?") if x == "deposit": myaccount.deposit(int(float(raw_input("how deposit?")))) print "total balance is: ", myaccount.balance() elif x == "withdraw": myaccount.withdraw(int(float(raw_input("how withdraw?")))) print "total balance is: ", myaccount.balance() else: print "please choose 'withdraw' or 'deposit'. thank you." what __init__ doing or storing. don't understand "self.amount" or how making = deposit anything. "self.amount" under __init__ same 1 under withdraw? i'm not understanding "self_amount" does.
q __init__ doing or storing?
a __init__ gets called whenever construct instance of class. applies classes. customary initialize data in function. in particular case, creating member data called amount , assigning same deposit argument passed function.
q don't understand "self.amount" or how making = deposit anything.
a statement self.amount = deposit accomplishes couple of things. creates member data of class named amount , assigns value of deposit.
q "self.amount" under __init__ same 1 under withdraw?
a yes.
q i'm not understanding "self.amount" does.
a allows capture data of object. every class needs figure out member data needs work correctly. in case, data need amount. if had class called employee, might like:
class employee(object): def __init__(self, firstname, lastname, id, salary): self.firstname = firstname self.lastname = lastname self.id = id self.salary = salary
Comments
Post a Comment