Practical on Unit V
Practical on Unit V
Classes and Objects: classes and objects, class method and self-
argument, __init__() method, class
variables and object variables, __del__() method, public and private
members, Built in function to
check, Get, Set and Delete class attribute, Garbage collection, class
methods, Static Method.
class Car:
def __init__(self, brand, model):
self.brand = brand # Attribute(Data members)
self.model = model # Attribute(Data Members)
class Dog(Animal):
def speak(self):
print("Dog barks")
# Message passing
dog = Dog()
dog.speak() # Calls the Dog’s speak method
3. Inheritance
● Allows a class (child) to derive properties and behavior from
another class (parent).
● Promotes code reuse and hierarchical classification.
Example:
class Vehicle:
def __init__(self, brand):
self.brand = brand
def show_brand(self):
print(f"Brand: {self.brand}")
class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand)
self.model = model
def show_details(self):
print(f"Car: {self.brand} {self.model}")
# Using inheritance
car = Car("Honda", "Civic")
car.show_details()
4. Polymorphism
● A subclass provides a specific implementation of a method already
defined in the parent class.
class Shape:
def area(self):
return 0
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
circle = Circle(5)
print(circle.area()) # Calls overridden method in Circle class
5. Containership (Composition)
● Containership (Composition): A class contains objects of another
class to reuse functionality.
class Engine:
def start(self):
print("Engine started")
class Car:
def __init__(self):
self.engine = Engine() # Car has an Engine
def start_car(self):
self.engine.start() # Delegating to Engine
# Containership in action
car = Car()
car.start_car()
6. Reusability
● OOP allows reusing existing code through inheritance and
containership.
7. Delegation
● Delegation allows one object to delegate a task to another.
class Printer:
def print_message(self, message):
print(message)
class Computer:
def __init__(self):
self.printer = Printer()
# Delegation
pc = Computer()
pc.delegate_printing("Hello, OOP!")
8. Data Abstraction
● Hiding complex implementation details and exposing only
necessary parts.
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass # Abstract method
class Dog(Animal):
def make_sound(self):
return "Bark"
dog = Dog()
print(dog.make_sound())
9. Encapsulation
● Hiding data using private (__) attributes.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable
def get_balance(self):
return self.__balance
# Encapsulation in action
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Accessing through method
======================================================
======================================================
Class method and self-argument-
In Python, a class method and the self argument are related to object-
oriented programming but serve different purposes.
1. self Argument
● The self parameter is used in instance methods of a class.
● It represents the instance (object) of the class and allows access to
its attributes and methods.
Example:
class Car:
def __init__(self, brand):
self.brand = brand # Instance attribute
def show_brand(self):
print(f"The car brand is {self.brand}")
# Creating an instance
my_car = Car("Toyota")
2. Class Methods
● Defined using the @classmethod decorator.
● Take cls as the first parameter instead of self, representing the
class itself.
● Can modify class-level attributes and work with the class rather
than instances.
Example:
class Car:
brand = "Generic" # Class attribute
@classmethod
def change_brand(cls, new_brand):
cls.brand = new_brand # Modifies class-level attribute
# Creating instances
car1 = Car("Model S")
car2 = Car("Model 3")
=======================================================
=======================================================
__init__() method
Syntax:
class MyClass:
def __init__(self, param1, param2):
self.param1 = param1
self.param2 = param2
How it Works:
● The __init__() method takes self as its first argument, which refers
to the instance being created.
● Additional parameters can be passed to initialize instance
attributes.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating an instance
p1 = Person("Alice", 25)
# Accessing attributes
print(p1.name) # Output: Alice
print(p1.age) # Output: 25
Key Points:
● The __init__() method is optional, but if defined, it is automatically
executed when an object is created.
● It does not return anything (None).
● It is used to set initial values for object attributes.
===================================================
Class Variable and Object variable-
1. Class Variables
In Python, class variables and instance (object) variables are two
different types of variables used in object-oriented programming. Here's
how they differ:
1. Class Variables
● Defined inside a class but outside any instance methods.
● Shared among all instances of the class.
● Changes to a class variable affect all instances unless an instance
overrides it.
● Declared directly in the class body.
class Car:
wheels = 4 # Class variable (shared by all instances)
car1 = Car("Toyota")
car2 = Car("Honda")
print(car1.wheels) # Output: 4
print(car2.wheels) # Output: 4
print(car1.wheels) # Output: 6
print(car2.wheels) # Output: 6
Example:
class Car:
wheels = 4 # Class variable
======================================================
__del__()
Syntax
class MyClass:
def __del__(self):
print("Destructor called. Object is being deleted.")
obj = MyClass()
del obj # Explicitly deleting the object
Key Points About __del__()
Automatic Invocation:
The __del__() method is automatically called when an object is
no longer in use.
Garbage Collection:
In Python, memory management is handled by garbage collection.
When an object has no references, the garbage collector deletes it and
calls __del__().
Explicit Deletion:
You can force the deletion of an object using del object_name, but
this doesn’t guarantee immediate execution of __del__(), as Python
decides when to run garbage collection.
Use Cases:
Example
class FileHandler:
def __init__(self, filename):
self.file = open(filename, 'w')
print(f"File {filename} opened.")
def __del__(self):
self.file.close()
print("File closed.")
# Creating an instance
handler = FileHandler("example.txt")
======================================================
======================================================
In object-oriented programming (OOP), public and private members
define the accessibility of variables (fields) and methods (functions)
inside a class.
Public Members
● Those variables that are defined in the class and can be accessed
from within the class and from outside the class.
● All members in a python class are public default.
● Accessible from anywhere: Other classes and external code can
access public members.
class Car:
def __init__(self, brand):
self.brand = brand # Public member
def show_brand(self):
print("Brand:", self.brand)
car = Car("Toyota")
print(car.brand) # Allowed
car.show_brand() # Allowed
Private Members
● Accessible only inside the class: They cannot be accessed directly
from outside.
● Those variables that are defined in the classand can be accessed
from within the class and from outside the class.
● The private variable are used with double underscore(_ _)prefix
class Car:
def __init__(self, brand):
self.__brand = brand # Private member (double underscore)
def show_brand(self):
print("Brand:", self.__brand)
car = Car("Toyota")
# print(car.__brand) # ❌ AttributeError: private
variable
car.set_brand("Honda") # ✅ Allowed via setter
method
car.show_brand()
======================================================
======================================================
Built in function to
check, Get, Set and Delete class attribute
In Python, built-in functions exist to check, get, set, and delete class
attributes dynamically. These functions are:
1. hasattr(obj, attr_name) – Checks if an attribute exists.
2. getattr(obj, attr_name, default) – Gets the attribute value.
3. setattr(obj, attr_name, value) – Sets the attribute to a value.
4. delattr(obj, attr_name) – Deletes the attribute.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 25)
# Delete an attribute
delattr(p, "age")
print(hasattr(p, "age")) # False
Garbage collection
● Garbage collection (GC) in Python is an automatic memory
management feature that helps free up memory occupied by
objects that are no longer in use. It is mainly handled by Python's
built-in garbage collector, which is part of the gc module.
● Python's gc module provides functions to interact with the garbage
collector.
1. Check if GC is enabled
import gc
print(gc.isenabled()) # Returns True if GC is enabled
2. Manually Trigger Garbage Collection
gc.collect() # Forces collection of unused objects
3. Disable and Enable GC
gc.disable() # Turns off garbage collection
gc.enable() # Turns it back on
=-
======================================================
=====================================================
@classmethod
def class_method(cls):
return f"Class method called. class_variable = {cls.class_variable}"
Key Points:
● Uses @classmethod decorator.
● The first parameter (cls) refers to the class, not an instance.
● Can modify class attributes but not instance attributes.
======================================================
======================================================
Example:
class MathOperations:
@staticmethod
def add(a, b):
return a + b
Key Points:
● Uses @staticmethod decorator.
● No access to class (cls) or instance (self) attributes.
● Used for utility functions related to the class.
●
======================================================
======================================================
8. Create class EMPLOYEE for storing details (Name, Designation,
gender, Date of Joining and Salary). Define function members to
compute a)total number of employees in an organization
class EMPLOYEE:
total_employees = 0 # Class variable to track total employees
@classmethod
def get_total_employees(cls):
return cls.total_employees
def display_details(self):
print(f"Name: {self.name}, Designation: {self.designation}, Gender: {self.gender},
Date of Joining: {self.date_of_joining}, Salary: {self.salary}")
# Example Usage
emp1 = EMPLOYEE("Alice", "Manager", "Female", "2022-05-10", 75000)
emp2 = EMPLOYEE("Bob", "Developer", "Male", "2021-08-15", 60000)
emp3 = EMPLOYEE("Charlie", "Analyst", "Male", "2023-01-20", 50000)