OOPS
Object-Oriented Programming System
- Ability to model real-world application in a much more effective fashion
-
Code reusability is high which results into lesser coding time
-
Provides flexibility in the modification of an existing application which refactoring
-
More maintainable code throughout the project
OOP in Python
- Everything in Python is an object.
>>> type([1, 2, 3])
<class 'list'>
Creating a Class
- The class statement creates a new class definition
class Employee:
pass
emp1 = Employee()
print(emp1)
<__main__.Employee instance at 0x109c2ecb0>
Example of a class
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print(f"Total Employee {Employee.empCount}")
def displayEmployee(self):
print(f"Name : {self.name}, Salary: {self.salary}")
Creating & Accessing Objects
#This would create first object of Employee class
emp1 = Employee("Ramesh", 10000)
#This would create second object of Employee class
emp2 = Employee("Suresh", 15000)
emp1.displayEmployee()
emp2.displayEmployee()
print(Employee.empCount)
- You can add, remove, or modify attributes of classes and objects at any time −
-
The getattr(obj, name[, default]) − to access the attribute of object.
-
The hasattr(obj,name) − to check if an attribute exists or not.
-
The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be created.
-
The delattr(obj, name) − to delete an attribute.
emp1.age = 7 # Add an 'age' attribute.
emp1.age = 8 # Modify 'age' attribute.
del emp1.age # Delete 'age' attribute.
Do it.
class Phone_book():
def __init__(self):
self.contact_details = {}
def add_contact(self, name, number):
#add contact to contact details
def remove_contact(self, name):
#Remove contact if available
#Else show error message
def get_contact_number(self, name):
#Get contact number if available
#Else show error message
def main():
john = Phone_book()
john.add_contact("Dad","+919590283524")
print(john.get_contact_number("Dad"))
if __name__ == "__main__":
main()
class Phone_book():
def __init__(self):
self.contact_details = {}
def add_contact(self, name, number):
self.contact_details[name] = number
def remove_contact(self, name):
if name in self.contact_details:
del self.contact_details[name]
else:
print("Contact not available")
def get_contact_number(self, name):
if name in self.contact_details:
return self.contact_details.get(name, None)
else:
print("Contact not available")
def main():
john = Phone_book()
john.add_contact("Dad","+919590283524")
print(john.get_contact_number("Dad"))
if __name__ == "__main__":
main()
Destroying Objects
class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print(class_name, "destroyed")
pt1 = Point()
pt2 = pt1
pt3 = pt1
print(id(pt1), id(pt2), id(pt3)) # prints the ids of the obejcts
del pt1
del pt2
- Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space.
- Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero.
Inheritance
Object oriented way of becoming wealthy.
class Dad():
def complexion(self):
return "fair"
def height(self):
return "tall"
def field_of_study(self):
return "Chemical Engineering"
class John(Dad):
def hair_color(self):
return "white"
my_description = John()
print(f"John is {my_description.complexion()} in complexion")
print(f"John is studying {my_description.field_of_study()}")
print(f"John hair color is {my_description.hair_color()}")
Multiple Inheritance.
class Dad():
def complexion(self):
return "fair"
def height(self):
return "tall"
def field_of_study(self):
return "Chemical Engineering"
class Mom():
def occupation(self):
return "entreprenuer"
class John(Dad, Mom):
def hair_color(self):
return "white"
my_description = John()
print(f"John is an {my_description.occupation()}")
Overriding Methods
class Mom():
def complexion(self):
return "dark"
def occupation(self):
return "entrepreneur"
class John(Mom):
def complexion(self):
return "fair"
description = John()
print(f"John is {description.complexion()} in complexion.")
print(f"John is an {description.occupation()}")
Overloading Operators
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return f"Vector ({self.a}, {self.b})"
def __add__(self, other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2, 10)
v2 = Vector(5, -2)
print(v1 + v2)
Data Hiding
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print(self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print(counter.__secretCount)
print(counter._JustCounter__secretCount)
- Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName.
Do it
class Bitcoin():
def __init__(self):
def buy_bitcoin(self, amount):
def sell_bitcoin(self, btc):
def available_bitcoin(self):
def __str__(self):
def main():
my_wallet = Bitcoin()
print("1 Bitcoin has value $100")
buy_amt = float(input("Enter amount to buy bitcoin for"))
my_wallet.buy_bitcoin(buy_amt)
print(my_wallet)
if __name__ == "__main__":
main()
"Sometimes it's better to leave something alone, to pause, and that's very true of programming." - Joyce Wheeler
[S4] Algo Trading with Python
By sumit12dec
[S4] Algo Trading with Python
- 277