#define a class class User : def __init__(self,name,user_id,acc_balance): self.Name=name self.User_id=user_id self.Acc_Balance=acc_balance def recharge(self,amount): self.Acc_Balance+=amount def withdraw(self,amount): if amount <= self.Acc_Balance : self.Acc_Balance-=amount else : pass #do nothing def getBalance(self): #parameter less method return self.Acc_Balance def __del__(self) : print("Destructor started!") #end of the class usr=User("Kanishka",1133,27000.00) print("User {0} , Balance {1:5.2f}".format(usr.Name,usr.getBalance())) usr.withdraw(2000.50) #withdrwaw money print("User {0} , Balance {1:5.2f}".format(usr.Name,usr.getBalance()))Python has mainly 3 access modifiers
- public
- protected : Variable name started with single _ character (ex: _userName )
- private : Variable name started with tow _ character (ex: __userName )
#define a class class User : def __init__(self,name,user_id,acc_balance): self.__Name=name #private self.__User_id=user_id #private self.__Acc_Balance=acc_balance #private def recharge(self,amount): self.Acc_Balance+=amount def withdraw(self,amount): if amount <= self.__Acc_Balance : self.__Acc_Balance-=amount else : pass #do nothing def getBalance(self): #parameter less method return self.__Acc_Balance def getUserName(self) : return self.__Name def __del__(self) : print("Destructor started!") #end of the class usr=User("Kanishka",1133,27000.00) print("User {0} , Balance {1:5.2f}".format(usr.getUserName(),usr.getBalance())) usr.withdraw(2000.50) #withdrwaw money print("User {0} , Balance {1:5.2f}".format(usr.getUserName(),usr.getBalance()))
- Inheritane
Note : Python supports multiple inheritance
Code :
class Person : def __init__(self,nic,name,address) : self._name=name #protected self._nic=nic self._address=address def __del__(self) : print("Destructor started!") #class ended class Employee(Person) : #inherit the person class def __init__(self,nic,name,address,employeeID,salary): Person.__init__(self,nic,name,address) self._employeeID=employeeID self._salary=salary def __del__(self) : print("Destructor started!") #class ended p=Person("832355234V","Saman","Sri Lanka") print ("Person instance") print ("Name : {} ".format(p._name)) e=Employee("881302333V","Kanishka","Sri Lanka",2328,20000) print ("Employee instance") print ("Name : {} ".format(e._name)) print ("employeeID : {0:d} ".format(e._employeeID))
0 comments:
Post a Comment