OOP
Python Chapter IV
Class and Object
print("OOP - Object Oriented Programming")
# class
class Fruit:
colour = "Red"
Apple = Fruit()
print(Apple.colour)
# del object
del Apple
# print(Apple.colour) - Error
# Multiple - object created
Dragon_Fruit=Fruit()
print(Dragon_Fruit.colour)
#pass statement
class Fruit:
pass
# __init__ -> method
class Fruit:
def __init__(self,colour):
self.colour = colour
Apple=Fruit("Red")
Orange=Fruit("Orange")
print(f"The Apple colour is : {Apple.colour}")
print(f"Orange Fruit colour is : {Orange.colour}")
# Multiple parameter in __init__ function
class Fruit:
def __init__(self,colour,count):
self.colour = colour
self.count=count
Apple=Fruit("Red",8)
Orange=Fruit("Orange",9)
print(f"The Apple colour is : {Apple.colour}")
print(f"Orange Fruit colour is : {Orange.colour}")
print(Apple.count)
#Default value in __init__
class Fruit:
def __init__(myobject,colour,count=0):
myobject.colour = colour
myobject.count=count
Apple=Fruit("Red",8)
Orange=Fruit("Orange")
print(f"Orange Count : {Orange.count}")# output
OOP - Object Oriented Programming
Red
Red
The Apple colour is : Red
Orange Fruit colour is : Orange
The Apple colour is : Red
Orange Fruit colour is : Orange
8
Orange Count : 0Class Properties and Object Properties
Properties defined outside methods belong to the class itself (class properties) and are shared by all objects
Properties defined inside __init__() belong to each object (instance properties).
class Person:
species = "Human" # Class property
def __init__(self, name):
self.name = name # Instance property
def greet(self):
print("Hello!")
p1 = Person("John")
p2 = Person("Tom")
#Access
print(p1.name)
print(p2.name)
print(p1.species)
print(p2.species)
#Modifying Class Properties
Person.species="People"
print(p1.species)
print(p2.species)
#Add New Properties
p1.age=39
Person.count=1
print(p1.age)
print(p1.count)
print(p1.greet())
# Delete Properties
del p1.age
print(p1.name) # This works
# print(p1.age) # This would cause an error
#del method
del Person.greet#output
John
Tom
Human
Human
People
People
39
1
Hello!
None
JohnThe __str__() Method
The
__str__()method is a special method that controls what is returned when the object is printed
# without __str__
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Emil", 36)
print(p1)
#output
<__main__.Person object at 0x7bd8b4665be0>
#with __str__ method
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} ({self.age})"
p1 = Person("Tobias", 36)
print(p1)
#output
Tobias (36)Static
#Static method
class Math:
@staticmethod
def add(a, b):
return a + b
print(Math.add(10, 5)) # No object needed
class Fruit:
category = "Food" # static/class variable
def __init__(self, name):
self.name = name # instance variable
#output
15
---------------------------------------------------------------------------
# order of execution
class Demo:
print("1. Class is being defined (Static Block)") # static-like
def __init__(self):
print("2. Inside __init__ (constructor)")
def normal(self):
print("3. This is a normal method")
print("----Creating object----")
d = Demo()
print("----Calling normal method----")
d.normal()
#output
1. Class is being defined (Static Block)
----Creating object----
2. Inside __init__ (constructor)
----Calling normal method----
3. This is a normal method
----------------------------------------------------------------------
# def add(self, numbers) -> int: -> it was hint the method return the integer as a output
class Calculator:
def add(self, numbers: list) -> int:
total = sum(numbers)
return total
calc = Calculator()
print(calc.add([10,20,30]))
#output
60If __name__ == “__main__”
fruit.py
def add(a, b):
return a + b
print("This is fruit file running")
if __name__ == "__main__":
print("Main block working")
print(add(10, 20))
#output
This is fruit file running
Main block working
30test.py
import fruit
#output
Fruit pythonOOP Principle
1. Inheritance
Inheritance allows one class to reuse properties and methods of another class.
It helps avoid code duplication and supports reusability.
print("Inheritance")
class Parent:
pass
class Child(Parent):
passTypes of Inheritance
— — — — — — — — — — — -
Single Inheritance
class Animal:
def __init__(self,name):
self.name=name
class Name_of_Animal(Animal):
def __init__(self,name):
super().__init__(name)
print(self.name)
# super() → calls the parent class method
Dog=Name_of_Animal("Dog")
Lion=Name_of_Animal("Lion")
#output
Dog
LionMultilevel Inheritance
'''
class A
|
class B
|
class C
'''
class GrandParent:
def show1(self):
print("GrandParent")
class Parent(GrandParent):
def show2(self):
print("Parent")
class Child(Parent):
def show3(self):
print("Child")
c = Child()
c.show1()
c.show2()
c.show3()
#output
GrandParent
Parent
ChildMultiple Inheritance
'''
class A class B
|
class c
'''
class Father:
def skill1(self):
print("Driving")
class Mother:
def skill2(self):
print("Cooking")
class Child(Father, Mother):
pass
c = Child()
c.skill1()
c.skill2()
#output
Driving
CookingHierarchical Inheritance
class Parent:
pass
class Child1(Parent):
pass
class Child2(Parent):
passHybrid Inheritance
- Combination of two or more types.
Get Datawhiz’s stories in your inbox
Join Medium for free to get updates from this writer.
2. Polymorphism
- Many Form
Types of Polymorphism
Method Overriding — Runtime Polymorphism
- Child class changes parent class method.
class Animal:
def sound(self):
print("Animal makes sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
a1 = Dog()
a1.sound()
# a2 = Animal()
# a2.sound() output - Animal makes sound
#output
Dog barks
# print(isinstance(c, Child)) # True
# print(isinstance(c, Parent)) # True
# print(issubclass(Child, Parent)) # True
print(isinstance(a1, Dog)) # True
print(isinstance(a1, Animal)) # True
print(issubclass(Dog,Animal)) # TrueMethod Overloading
- Python Not support this instead they have a *args function
Encapsulation
Encapsulation means binding data (variables) and methods (functions) together inside a class and controlling access to them.
- Data hiding + data protection
without this
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
s = Student("John", 95)
s.marks = 200 # Wrong but allowed - Anyone can change data.
print(s.marks)
#output
200Access Modifiers
1. Public Members
class Employee:
def __init__(self, name):
self.name = name # public
e = Employee("Ram")
print(e.name) # Allowed
#output
Ram2. Protected Members _
class Bank:
def __init__(self):
self._balance = 5000
class Customer(Bank):
def show(self):
print(self._balance)
c = Customer()
c.show()
#output
50003. Private Members __
class Bank:
def __init__(self):
self.__balance = 10000
def show_balance(self):
print(self.__balance)
b = Bank()
b.show_balance() # work perfectly
# print(b.__balance) Error
#output
10000Name Mangling
Private variables are renamed internally:
print(b._Bank__balance) # Works but not recommended
#output
10000Getter and Setter
class Account:
def __init__(self):
self.__balance = 0
def get_balance(self):
return self.__balance
def set_balance(self, amount):
if amount >= 0:
self.__balance = amount
else:
print("Invalid amount")
a = Account()
a.set_balance(5000)
print(a.get_balance())
#output
5000Using @property (Pythonic Way )
class Account:
def __init__(self):
self.__balance = 0
@property
def balance(self):
return self.__balance
@balance.setter
def balance(self, amount):
if amount >= 0:
self.__balance = amount
else:
print("Invalid")
a = Account()
a.balance = 3000
print(a.balance)
#output
3000Python Inner Classes
- An inner class is a class defined inside another class.
- It is used when the inner class is closely related to the outer class and should not be used independently.
Syntax
class Outer:
class Inner:
passclass Car:
a = 90
class Engine:
def __init__(self, outer_obj):
self.outer = outer_obj
def engine_type(self):
print("Petrol Engine")
print(self.outer.a)
c = Car()
# Access Inner Class Using Outer Class Object
# Accessing Outer Class from Inner Class
e = Car.Engine(c)
e.engine_type()
#output
Petrol Engine
90

