Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

NAME : Chirag Lakhotia ROLL NO : 20214006

Classes in Python

Introduction

Python, a versatile and widely used programming language, embraces


object-oriented programming (OOP) principles. Classes, a fundamental
OOP concept, serve as blueprints for creating objects that encapsulate
data (attributes) and behavior (methods). This report delves into classes
in Python, exploring their definition, structure, usage, and practical
examples.

Defining a Class

The class keyword is the cornerstone for creating a class in Python.


Here's the basic structure:

Python class
ClassName: #
Class body
# Attributes (variables) and methods (functions)
pass

• ClassName: This represents the name you assign to your class,


typically starting with a capital letter and using PascalCase (e.g.,
Car, BankAccount).
• Class body: This indented section houses the class's internal
components:
o Attributes (variables): These store data specific to objects
(instances) of the class. They're either defined directly within the
class or dynamically created within methods. o Methods
(functions): These define the behavior (operations) that objects
can perform. Methods operate on the object's attributes and can
potentially interact with other objects. A special method named
__init__(self, ...) is often used to initialize attributes
when a new object is created.

Example: Creating a Car Class

Python class
Car:
def __init__(self, make, model, year): #
Constructor (initialization method)
self.make = make self.model
= model self.year = year
def accelerate(self): # Behavior
method print(f"{self.make}
{self.model} is accelerating!")

def brake(self): # Behavior method


print(f"{self.make} {self.model} is braking!")

In this example:

• The Car class encapsulates car-related attributes like make, model,


and year.
• The __init__() method (constructor) is called when a new Car
object is created using the Car() syntax. It takes an instance (the
object itself, represented by self) and initial values for the
attributes.
• The accelerate() and brake() methods define car behaviors
and are invoked using dot notation (e.g., myCar.accelerate()).

Class Polymorphism in Python :


Because Python allows various classes to have methods with the same
name, we can

leverage the concept of polymorphism when constructing class methods.


We may then
generalize calling these methods by not caring about the object we're
working with. Then

we can write a for loop that iterates through a tuple of items.

Example :
class Tiger():

def nature(self):

print('I am a Tiger and I am dangerous.')

def color(self):

print('Tigers are orange with black strips')

class Elephant():

def nature(self):

print('I am an Elephant and I am calm and harmless')

def color(self):

print('Elephants are grayish black')

obj1 = Tiger()

obj2 = Elephant()

for animal in (obj1, obj2): # creating a loop to iterate through the obj1 and obj2

animal.nature()

animal.color()

Output :
I am a Tiger and I am dangerous.

Tigers are orange with black strips

I am an Elephant and I am calm and harmless

Elephants are grayish black


We've created two classes here: Tiger and Elephant. They have the same structure and

the same method names, nature() and color ().

However, you'll see that we haven't built a common superclass or connected the classes in

any manner. Even so, we may combine these two objects into a tuple and iterate over it

using a common animal variable. Because of polymorphism, it is conceivable.

Creating Objects (Instances)

Once you've defined a class, you can create objects (instances) of that
class:

Python
myCar = Car("Tesla", "Model S", 2023) # Create a Car
object
anotherCar = Car("Ford", "Mustang", 2022)

• myCar and anotherCar are distinct objects (instances) belonging


to the Car class.
• You can access and modify object attributes using dot notation (e.g.,
myCar.make, myCar.accelerate()).

Methods: The Power of Objects

Methods are the heart of object-oriented programming. They define how


objects interact with their data and with each other.

Python
myCar.accelerate() # Output: Tesla Model S is
accelerating!
anotherCar.brake() # Output: Ford Mustang is
braking!
Summary

Classes in Python provide a powerful and organized way to create


objects that encapsulate data and behavior. By defining classes, you can
create reusable templates for objects, promote code modularity, and
make your programs more maintainable and scalable.

Additional Considerations

• Inheritance: Classes can inherit attributes and methods from parent


(base) classes, enabling code reuse and specialization.
• Encapsulation: Classes can enforce data protection through
access modifiers (public, private, protected), controlling attribute
visibility and modification.
• Polymorphism: Classes can participate in polymorphism, which
allows objects of different classes to respond to the same method
call in unique ways.

• Operator Overloading: You can define how operators (e.g., +, -)


work with your class objects.
• Class Variables: You can define variables shared among all
instances of a class using the @classmethod decorator.

By understanding and applying classes effectively, you can write


wellstructured, object-oriented Python programs that are efficient,
maintainable, and easier to collaborate on. Feel free to explore these
advanced concepts as you delve deeper into OOP!

You might also like