Basic Structure of OOP in Python
Objects are instances of Classes
– Can have multiple objects of the same Class type
– E.g., You would be an instance of the Human class: you have the properties of your Class(Human)
– No main()
function (Class is not a program)
Classes
- are blueprints or templates for creating objects.
- They encapsulate data (attributes) and behaviors (methods) that objects of that class can exhibit.
class ClassName:
# Attributes (data)
def __init__(self, params):
self.attribute = params
# Methods (behaviors)
def method(self):
# Method body
class Classname:
def __init__(self, additional parameters):
# Constructor
body
self.variable_name = value # example instance variable
# Method
def method_name(self, additional parameters):
body
Objects (Instances):
- Objects are instances of classes.
- Object Creation using the class name followed by parentheses ().
obj = ClassName(params)
Attributes
- Variables that belong to a class/object.
obj.attribute
Method
- Functions defined within a class that perform operations on objects of that class.
obj.method()
TASK
- Practice with Examples:
- Write and execute sample code to understand how classes, objects, attributes, and methods interact.
- Visualize Concepts:
- Draw diagrams or flowcharts to visualize class hierarchies, attribute access, and method invocation.
Example Square class
class Square:
def __init__(self, side):
# method
self.side = side
# (self.side) called class member
def area(self):
return self.side*self.side
s1 = Square(2)
print(s1.area())
Example rectangle class
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def __str__(self):
# __str__ for better object representation
return f"Rectangle(width={self.width}, height={self.height})"
# to handle user input with error handling.
def create_rectangle():
while True:
try:
width = float(input("Enter the width of the rectangle: "))
height = float(input("Enter the height of the rectangle: "))
return Rectangle(width, height)
except ValueError:
print("Invalid input. Please enter numeric values for width and height.")
# Create a rectangle with user input
r1 = create_rectangle()
print(r1)
# Print the area of the rectangle
print(f"Area of the rectangle: {r1.area()}")
'''
OUTPUT
Enter the width of the rectangle: 3
Enter the height of the rectangle: 4
Rectangle(width=3.0, height=4.0)
Area of the rectangle: 12.0
'''
Example shape class
class Shape:
def __init__(self):
pass
def area(self):
raise NotImplementedError("Subclasses must implement this method")
def __str__(self):
return f"{self.__class__.__name__}"
class Rectangle(Shape):
def __init__(self, width, height):
super().__init__()
self.width = width
self.height = height
def area(self):
return self.width * self.height
def __str__(self):
return f"Rectangle(width={self.width}, height={self.height})"
class Triangle(Shape):
def __init__(self, base, height):
super().__init__()
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
def __str__(self):
return f"Triangle(base={self.base}, height={self.height})"
def create_shape():
shape_type = input("Enter the type of shape (rectangle/triangle): ").lower()
if shape_type == "rectangle":
width = float(input("Enter the width of the rectangle: "))
height = float(input("Enter the height of the rectangle: "))
return Rectangle(width, height)
elif shape_type == "triangle":
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
return Triangle(base, height)
else:
print("Invalid shape type")
return None
# Create a shape with user input
shape = create_shape()
if shape:
print(shape)
print(f"Area of the {shape}: {shape.area()}")
'''
Enter the type of shape (rectangle/triangle): rectangle
Enter the width of the rectangle: 2
Enter the height of the rectangle: 3
Rectangle(width=2.0, height=3.0)
Area of the Rectangle(width=2.0, height=3.0): 6.0
'''
Example
- code defines a class Hello that can be instantiated with a text string and then called like a function to print that text string.
- When
printer = Hello("Hello World")
is executed, it creates an instance of Hello withself.txt
set to “Hello World”. - When
printer()
is called, it triggers the__call__
method, which prints the value ofself.txt
, which is “Hello World”.
class Hello:
def __init__(self,gtext):
self.txt = gtext
'''
- constructor method for the Hello class =>
called when an instance of the class is created.
- It takes one parameter gtext and assigns it
to an instance variable self.txt.'''
def __call__(self):
print(self.txt)
'''
- special method allows an instance of the class
to be called as if it were a function.
- When an instance is called, it tries to print self.text.
'''
def main():
printer = Hello("Hello World")
# creates an instance of the Hello class with gtext set to "Hello World".
printer()
# tries to call the instance, which triggers the __call__ method.
try:
if __name__=="__main__":
# ensures that the main() function is called only if
# this script is executed directly, not if it is imported as a module.
main()
except Exception as e:
exit()
'''
- to handle any exceptions that might occur during the execution of main().
- If an exception occurs, the script will exit gracefully.
'''
Advantages of OOP:
- code reusability,
- modularity, and
- easier maintenance.
- classes are user definable data types
Principles of Object-Oriented Programming
- inheritance, and
- polymorphism
- encapsulation,
- abstraction
Basic Information Flow in OOP:
1. Instantiation:
- Creating an object (instance) of a class.
obj = ClassName()
2. Accessing Attributes:
Retrieve or modify the object’s data.
obj.attribute = value
3. Calling Methods:
- Invoke behaviors defined in the class.
obj.method()
4. Inheritance:
- Creating a new class from an existing class, inheriting its attributes and methods.
class ChildClass(ParentClass):
# Additional attributes and methods
5. Polymorphism:
- The ability to use a method from the parent class in a child class with different implementations.
class ChildClass(ParentClass):
def method(self):
# Override parent method
6. Encapsulation:
- Bundling data (attributes) and methods that operate on the data into a single unit (class), and restricting access to some of the object’s components.
class ClassName:
def __init__(self, data):
self.__data = data # Private attribute
def method(self):
# Access private attribute within the class
return self.__data
back |