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__)
Sunday, 15 April 2018
Python - OOPS Basics-eg1 - Day 25(4 days later)
Python - OOPS Basics - Day 25(4 days later)
#everything is objects in python
#take away : class and objects
# a = 1
# b = 3
# print (a + b)
# print (a.__add__(b))
#so + is same as __add__ ,if u ctrl right click it will goto the same definition
class kettle (object):
power_source = 'fuel'
def __init__(self,make,price):
self.make = make
self.price = price
self.on = False
def switch_on(self):
self.on = True
kenwoodobj = kettle('kenwood',25)
hamilton = kettle('hamilton',30)
print(kenwoodobj.make)
print(hamilton.make)
print(hamilton.price)
hamilton.make = 'Hamiltoon'
print(hamilton.make)
print(kenwoodobj)
print ('{}={},{}={}'.format(kenwoodobj.make,kenwoodobj.price,hamilton.make,hamilton.price))
kenwoodobj1 = kenwoodobj
print(id(kenwoodobj1))
print(id(kenwoodobj))
print(id(hamilton))
print(id(hamilton.make))
#we can call the object by
#classname.objectname(instancename)
#or
#instancename.objectname()
kettle.switch_on(hamilton)
print(hamilton.make)
print(hamilton.on)
hamilton.on = False
print(hamilton.on)
hamilton.switch_on()
print(hamilton.on)
#this is called as instance variable,variable is only for this instance,not for the entire instances of the
#class
kenwoodobj.power = 1.5
print(kenwoodobj.power)
#if we try accessing the same variable for different instance,it will throw error
# print(hamilton.power)
print (kettle.power_source)
print (kenwoodobj.power_source)
print (hamilton.power_source)
print(kettle.__dict__)
print(kenwoodobj.__dict__)
print(hamilton.__dict__)
print ('*' * 80)
# kettle.power_source = 'atomic'
print (kettle.power_source)
print (kenwoodobj.power_source)
print (hamilton.power_source)
print(kettle.__dict__)
print(kenwoodobj.__dict__)
print(hamilton.__dict__)
print ('/' * 80)
#if we assign the value for the calss attribute instance,it becomes instance vriable and remains
#unaffected for the class and other instances
kenwoodobj.power_source = 'gas'
print (kettle.power_source)
print (kenwoodobj.power_source)
print (hamilton.power_source)
print(kettle.__dict__)
print(kenwoodobj.__dict__)
print(hamilton.__dict__)
print ('*' * 80)
hamilton.power_source = 'fossil fuel'
print (kettle.power_source)
print (kenwoodobj.power_source)
print (hamilton.power_source)
print(kettle.__dict__)
print(kenwoodobj.__dict__)
print(hamilton.__dict__)
hamilton.power_source = 'fuel'
print (kettle.power_source)
print (kenwoodobj.power_source)
print (hamilton.power_source)
print(kettle.__dict__)
print(kenwoodobj.__dict__)
print(hamilton.__dict__)
print ('@' * 80)
kettle.power_source = 'fuel'
print (kettle.power_source)
print (kenwoodobj.power_source)
print (hamilton.power_source)
print(kettle.__dict__)
print(kenwoodobj.__dict__)
print(hamilton.__dict__)
#this will explain you how to document a program(DocString)
class song:
"""
class to represent a song
Attributes:
title():The tile of the song
artist(Artist):An artist object representing the songs creator
duration (int):The duration of the song in seconds.May be Zero
"""
def __int__(self,title,artist,duration=0):
"""song init method
Args:
title(str):Intialises the 'title' attribute
artist(Artist):An artist object representing the songs creator
duration (optional int):initialise value to 'duration' attribute
will be defaulted to zero if not specified.
"""
self.title = title
self.artist = artist
self.duration = duration
Python - scope and recursive function - Day 25(4 days later)
#take way:read the document related to local,nonlocal,global
#know what is LEGB - Local Enclosing Global Builtins
#below example will illustrate the variable and the scope of it
# def spam1():
# def spam2():
# def spam3():
# z = ' even more spam'
# print('3 {}'.format(locals()))
# return z
# y = 'more spam '
# y+= spam3()
# print('2 {}'.format(locals()))
# return y
# x = 'spam '
# x+= spam2()
# print('1 {}'.format(locals()))
# print(x)
def spam1():
def spam2():
def spam3():
# y = 'test'
z = ' even' + y
print('3 {}'.format(locals()))
return z
y = ' more'+x
y+= spam3()
print('2 {}'.format(locals()))
return y
x = 'spam'
x+= spam2()
# we can't write like this x = 'spam' + spam2(),since spam2 function first expects x
# it will throw unreferenced variable error if we code like that
print('1 {}'.format(locals()))
print(x)
print(spam1())
print(locals())
print(globals())
#recursive function,function that calls itself again and again
#factorial
def factorial(n):
result = 1
if n>1:
for i in range (1,n+1):
result = result * i
return result
def factorialrec(n):
#n factorial can also be defined as n * (n-1)!
if n<=1:
return 1
else:
return n * factorialrec(n-1)
def fibonaccirec(n):
# Fn = Fn-1 + Fn-2
if n<2:
return n
else:
return fibonaccirec(n-1)+fibonaccirec(n-2)
def fibonacci(n):
if n == 0:
return 0
if n == 1:
return 1
elif n==2:
return 1
else:
n_minus1 = 1
n_minus2 = 0
for i in range(1,n):
result = n_minus1+n_minus2
n_minus2 = n_minus1
n_minus1 = result
return result
# for x in range (1,130):
# print(x , factorial(x))
# for x in range (1,130):
# print(x , factorialrec(x))
# here use of the recursive funtion in calculating the fibonaaci
#might slow downb the process,so we can go for direct method
# for x in range (1,36):
# print(x , fibonaccirec(x))
#below direct method will be fast
for x in range (1,36):
print(x , fibonacci(x))
Subscribe to:
Posts (Atom)