0% found this document useful (0 votes)
17 views12 pages

Class and Object-Python

Object-Oriented Programming (OOP) is a programming paradigm that utilizes objects to represent real-world entities, emphasizing principles like encapsulation, abstraction, inheritance, and polymorphism. In Python, classes serve as blueprints for creating objects, with attributes and methods defined within them, while constructors and destructors manage object lifecycle. Inheritance allows classes to acquire properties from other classes, promoting code reusability and hierarchy representation.

Uploaded by

jpxvdesign
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views12 pages

Class and Object-Python

Object-Oriented Programming (OOP) is a programming paradigm that utilizes objects to represent real-world entities, emphasizing principles like encapsulation, abstraction, inheritance, and polymorphism. In Python, classes serve as blueprints for creating objects, with attributes and methods defined within them, while constructors and destructors manage object lifecycle. Inheritance allows classes to acquire properties from other classes, promoting code reusability and hierarchy representation.

Uploaded by

jpxvdesign
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Introduction to Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of


objects. Objects represent real-world entities and have attributes (data members) and
behavior (functions/methods). The main principles of OOP are:

1. Encapsulation – Wrapping data and methods into a single unit (class).


2. Abstraction – Hiding unnecessary details and showing only relevant features.
3. Inheritance – Acquiring properties from another class.
4. Polymorphism – Having multiple forms of the same function (method overloading
and method overriding).

What is a Class in Python?


A class is a blueprint for creating objects. It defines attributes (variables) and methods
(functions) that the objects will have. Think of a class as a template—for example, a "Car"
class defines common features (color, brand, speed), and we can create multiple car objects
using this template.

Defining a Class in Python

In Python, we define a class using the class keyword.

Understanding Class Data Members and Methods

 Data Members: These are variables inside the class (e.g., brand, color).
 Member Functions (Methods): These are functions defined inside a class that
perform operations (e.g., show_details).

In Python, the default visibility (access control) of class members (attributes and methods) is public.
This means that if you define a variable or method inside a class without any special naming
conventions, it is accessible from outside the class.

Example Usage of Class

Creating an object and accessing its data members and methods:


Instance (Object) vs. Class

 A class is a template (like a general concept of a "Car").


 An instance (object) is an actual entity created from the class (like a specific car with
a color).
 Each instance has its own data, separate from other instances. (Eg: car1=Car( ),
car2=Car( ). Here, car1 and car2 are instances of class Car. car1 and car2 has separate
values for brand, color etc)

Multiple Instances of the Same Class

Each instance is independent, meaning changing one instance’s attributes does not affect others:

Understanding self in Member Functions

In Python, self is a reference to the instance of the class that is calling the member function. It
allows the function to access and modify instance attributes and call other instance methods.

How self Works in This Example?

1. When calling s1.set_details("Alice", 20),

-self refers to s1, so self.name = "Alice" and self.age = 20.

2. When calling s2.set_details("Bob", 22),


-self refers to s2, storing "Bob" and 22 separately.

3. When calling s1.show_details(),

-It prints s1's attributes (Alice, 20).

Each object (s1, s2) has its own separate data because self ensures attributes are stored
per instance.

What Happens Without self?

If we remove self, Python will not know which object's attributes to modify, causing an error.

To fix the error in the incorrect example, we need to add self as the first parameter in the method.
Here’s the corrected version:

Explanation of the Fix

1. Added self in set_value(self, value)


o Now, self.value = value correctly assigns the value to the instance
attribute.
Constructors in Python
A constructor is a special method that automatically runs when an object is created. In Python, the
constructor method is named __init__(). It initializes object attributes.

A constructor initializes attributes when an object is created.

In the above code, when object s1 is created using Student(“Alice”), the name Alice is also assigned
to the object using the constructor __init__(). No other function is used here for object’s
initialisation.

Accessing and Modifying Attributes

We can access and change object attributes.

Step-By-Step Breakdown Of The Code Above


1. Class Definition:
o class Employee:defines a class named Employee.
2. Constructor (__init__) Initializes the Attribute:
o def __init__(self, name): is the constructor that runs when an object is
created.
o self.name = name assigns the passed value (name) to the object’s attribute
self.name.
3. Creating an Object:
o emp = Employee("John") creates an instance (object) of Employee, with
"John" stored in self.name.
4. Accessing an Attribute:
o print(emp.name) prints "John" because self.name was assigned "John".
5. Modifying an Attribute:
o emp.name = "David" changes the value of name from "John" to "David".
6. Printing the Updated Value:
o print(emp.name) now prints "David" since we updated the attribute.

Built-in Class Attributes

Python provides several built-in class attributes that store useful metadata about a class. These
attributes start and end with double underscores (__).

Common Built-in Class Attributes

Attribute Description

__dict__ Dictionary containing the class's namespace (attributes and methods).

__name__ The name of the class.

__module__ The module where the class is defined.

__bases__ A tuple containing the base classes of the class (used in inheritance).

__doc__ The docstring of the class (if provided).

Example: Using Built-in Class Attributes


Explanation

 Car.__name__ → Returns the name of the class (Car).


 Car.__doc__ → Returns the docstring ("This is a Car class").
 Car.__module__ → Returns the module name (__main__ if running directly).
 Car.__dict__ → Returns a dictionary of class attributes.

Destructors in Python (__del__())

A destructor is a special method called when an object is deleted or goes out of scope. In Python,
the destructor method is __del__().

Why Use a Destructor?

 It releases resources (e.g., closing files, network connections).


 It frees memory when an object is no longer needed.

Example: Destructor (__del__()) in Action


Explanation

1. Constructor (__init__) runs when an object is created, printing "Student Alice


created".
2. Destructor (__del__) runs when del s1 is executed, printing "Student Alice
deleted".

Note:

 Python automatically calls __del__() when an object is no longer needed.


 In most cases, Python's garbage collector handles memory cleanup, so __del__() is
rarely needed.

Inheritance in Python
1. Introduction to Inheritance

Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a child


class to acquire properties and behaviors (attributes and methods) from a parent class.

Why Use Inheritance?

 Code Reusability – Avoids rewriting the same code in multiple classes.


 Hierarchy Representation – Represents real-world relationships (e.g., Car → ElectricCar).
 Extensibility – Allows modifying existing code without changing the parent class.
Understanding Inheritance with an Example

Let’s consider a real-world example:

� Suppose we have a general Animal class, and we want to create a Dog class that inherits
properties of an animal but also has additional behavior.

Explanation

1. Animal is the parent class (or base class).


2. Dog is the child class (or derived class) that inherits from Animal.
3. The Dog class can use both:
o The inherited method speak() from Animal.
o Its own method bark().

Types of Inheritance in Python

Python supports different types of inheritance:

1. Single Inheritance

One child class inherits from one parent class.


2. Multiple Inheritance

A child class inherits from multiple parent classes.

3. Multilevel Inheritance

A class inherits from another class, which itself inherits from another class.
Hierarchical Inheritance

Multiple child classes inherit from the same parent class.


Overriding Parent Methods

The child class can override a method from the parent class by defining a new version of it.

Overriding in Python

Method Overriding is a feature of inheritance in which a child class provides a new


implementation for a method that is already defined in its parent class.

Key Points About Overriding

 The method name and parameters must be the same in both the parent and child
classes.
 The child class method replaces the parent class method when called from an instance
of the child class.

Data Hiding
In Python, data hiding, a core concept in object-oriented programming (OOP), involves
restricting access to internal data (attributes) of a class, typically by using a double
underscore prefix (__) to denote private members.

How Data Hiding Works in Python

1. Private Attributes (__var)


o In Python, attributes prefixed with double underscores (__) are considered
private.
o They cannot be accessed directly from outside the class.
2. Protected Attributes (_var)
o Attributes prefixed with a single underscore (_) indicate that they are
protected.
o They can still be accessed directly but are meant to be used only within the
class or its subclasses.

You might also like