Object-Oriented Programming (OOP) revolves around two main concepts: classes and objects.
In Python, we define a class using the class keyword:
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.brand} {self.model}")
# Creating an object (instance) of the class
my_car = Car("Toyota", "Corolla", 2022)
# Accessing attributes and methods
print(my_car.brand) # Output: Toyota
my_car.display_info() # Output: 2022 Toyota Corolla__init__() Method__init__() method is a special method (constructor) that initializes an object when it is created.self refers to the instance of the class and is used to access attributes and methods.You can create multiple objects from the same class:
car1 = Car("Honda", "Civic", 2023)
car2 = Car("Ford", "Mustang", 2021)
car1.display_info() # Output: 2023 Honda Civic
car2.display_info() # Output: 2021 Ford MustangAttributes of an object can be modified after creation:
my_car.year = 2023
print(my_car.year) # Output: 2023You can delete an attribute using del:
del my_car.yearTo check the type of an object:
print(isinstance(my_car, Car)) # Output: TrueClasses define a blueprint for objects.
Objects are instances of a class.
The __init__() method initializes objects.
Methods define behaviors, and attributes store data.
Multiple objects can be created from the same class.
Sign in to join the discussion and post comments.
Sign inPython for Web Development
Python for Web Development is a comprehensive tutorial series covering the fundamentals of building web applications using Flask and Django. From setting up a project to working with databases, authentication, REST APIs, and deployment on cloud platforms, this series provides a solid foundation for developing secure and scalable web applications.
Python Basics
Python is a powerful, high-level programming language known for its simplicity and versatility. It is widely used in various fields, including web development, data science, artificial intelligence, automation, and more. This tutorial series is designed to take you from the basics of Python to more advanced topics, ensuring a strong foundation in programming.