Sunday, 15 April 2018

Python - OOPS Basics-eg1 - Day 25(4 days later)

  • simple program on bank account concept,based on oops
  •   
    import datetime
    import pytz
    class Account:
    
        #this will be static method,ie it will be common for all instances(ie the class)
        #so while accessing it no need of using self
        @staticmethod
        def _current_time():
            utc_time = datetime.datetime.utcnow()
            return pytz.utc.localize(utc_time)
    
    
    
        def __init__(self,name,_balance):
            self._name =name
            self._transactiondetails_list = [(Account._current_time(), _balance)]
            self._balance = _balance
            print("Account Created for {}".format(self._name))
            self.showbalance()
    
        def deposit(self,amount):
            self._balance+=amount
            self.showbalance()
            self._transactiondetails_list.append((Account._current_time(), amount))
            # self.transactiondetails_list.append((pytz.utc.localize(datetime.datetime.utcnow()),amount))
            # print(self.transactiondetails_list)
    
        def withdraw(self,amount):
            if(0 < amount<=self._balance):
                self._balance-=amount
                self._transactiondetails_list.append((Account._current_time(), -amount))
            else:
                print("Amount should be greater than 0 and lesser than available balance")
            self.showbalance()
    
        def showbalance(self):
            print('Balance: ', self._balance)
    
        def showtransdetails(self):
            for date, amount in self._transactiondetails_list:
                if amount > 0:
                    tran_type ='Deposited'
                else:
                    tran_type ='Withdrwan'
                    amount*=-1
                print("{:6} {} on {} (local time was {})".format(amount,tran_type,date,date.astimezone()))
    
    udai = Account('udai',1000)
    #udai.withdraw(100)
    # udai.withdraw(200)
    # udai.deposit(200)
    # #we can update the balance variable to whatever we want outside of the class,so we can rename
    # #to _balance,which will also dont restrict to change , but user can know that
    # #it is for internal purpose and shouldn't be modified,similarly for the name and list variables
    # #which should not be modified after the instantiation
    # # udai.balance=0
    # udai.showbalance()
    # udai.showtransdetails()
    
    #its better not to mess with '_' and '__' objects which will produce strange results
    udai.showbalance()
    udai._balance = 10
    udai.showbalance()
    print('*'*40)
    print(udai.__dict__)
    print(Account.__dict__)
    udai.__balance = 49
    udai.showbalance()
    udai.showbalance()
    print(udai.__dict__)
    print(Account.__dict__)
     
    

    No comments:

    Post a Comment