Python Docs

Python OOP — Basics, Classes, and Objects

What is OOP?

Object-Oriented Programming (OOP) is a programming structure that organizes code around objects and classes.

Python is an object-oriented language. OOP makes code cleaner, reusable, easier to maintain, and follows the DRY (Don't Repeat Yourself) principle.

Advantages of OOP

  • Helps create clean and organized code
  • Improves code reuse through classes and objects
  • Makes programs easier to maintain and debug
  • Supports modular and scalable development

What are Classes and Objects?

A class is a blueprint for creating objects. It defines how an object behaves and what properties it has.

An object is an instance created from a class. When you create an object, it inherits everything defined inside the class.

Example Comparison

  • Class: Car — Objects: BMW, Audi, Tesla
  • Class: Fruit — Objects: Apple, Mango, Banana

Defining a Class

class MyClass:
  x = 10

This class contains one variable named x. A class can contain variables (attributes) and functions (methods).

Creating an Object

obj = MyClass()
print(obj.x)

Here, obj is an object created from MyClass. You can access class variables and methods through the object.

Summary

  • OOP organizes code using classes and objects
  • Class = Blueprint or template
  • Object = Created from a class
  • Objects inherit behaviors and properties from their class
  • OOP makes code reusable, modular, and clean