Spex3
    

Object-Oriented Programming (OOP) in Python ๐Ÿš€


    

    

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to structure code efficiently. Python supports OOP with features like encapsulation, inheritance, and polymorphism.

1๏ธโƒฃ Classes and Objects

What is a Class?

A class is a blueprint for creating objects. It defines attributes (variables) and methods (functions) that describe the objectโ€™s behavior.

What is an Object?

An object is an instance of a class. Multiple objects can be created from a single class.

2๏ธโƒฃ Defining a Class

๐Ÿ“Œ Use the class keyword to define a class.


class Car:
pass # Empty class (for now)

๐Ÿ”น Car is a class, but it doesn't do anything yet.

3๏ธโƒฃ Creating Objects (Instances of a Class)

๐Ÿ“Œ To create an object, call the class name like a function.


class Car:
pass

# Creating objects
car1 = Car()
car2 = Car()

print(type(car1)) # Output:
print(type(car2)) # Output:
๐Ÿ”น car1 and car2 are two separate objects of the Car class.

4๏ธโƒฃ Attributes and Methods

Attributes (Instance Variables)
๐Ÿ“Œ Attributes are variables that belong to an object. They define the state of an object.


class Car:
def __init__(self, brand, model, year): # Constructor
self.brand = brand # Attribute
self.model = model # Attribute
self.year = year # Attribute

# Creating objects with attributes
car1 = Car("Toyota", "Camry", 2022)
car2 = Car("Honda", "Civic", 2021)

print(car1.brand) # Output: Toyota
print(car2.model) # Output: Civic
๐Ÿ”น __init__() is a constructor that initializes object attributes.
๐Ÿ”น self.brand, self.model, self.year are instance attributes.

Methods (Functions inside a Class)

๐Ÿ“Œ Methods define behaviors of an object.


class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year

def display_info(self):
return f"{self.year} {self.brand} {self.model}"

# Creating an object
car1 = Car("Tesla", "Model S", 2023)

print(car1.display_info()) # Output: 2023 Tesla Model S
๐Ÿ”น display_info() is a method that returns car details.
๐Ÿ”น self allows access to object attributes inside methods.

5๏ธโƒฃ The self Keyword

๐Ÿ“Œ self represents the current instance of a class. It is used to access instance attributes and methods.


class Person:
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age # Instance variable

def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."

# Creating an object
p1 = Person("Alice", 30)

print(p1.greet()) # Output: Hello, my name is Alice and I am 30 years old.
๐Ÿ”น self.name refers to the name attribute of the current object.
๐Ÿ”น Without self, Python wonโ€™t know which object's attribute to access.


    Date: 2025-03-22 00:00:00.000000