Python Object-Oriented Programming

Classes and Objects

Object-Oriented Programming (OOP) in Python allows you to define custom data types using classes. A class is a blueprint for creating objects, which are instances of the class.

Syntax

Tutorials dojo strip

Example

  • The __init__ method is a constructor that initializes the attributes of the class. Methods are functions defined inside the class that operate on its attributes.

Instance and Class Variables

Instance variables are unique to each object instance, while class variables are shared among all instances of a class.

Example

  • wheels is a class variable, so its value is shared by all instances of the Car class. brand and model are instance variables, unique to each Car object.

Pillars of OOP

Python supports the four main pillars of Object-Oriented Programming:

Encapsulation

Bundling the data (attributes) and methods (functions) that operate on the data into a single unit, or class.

Example: In the Car class, the brand and model attributes are encapsulated within the class.

Abstraction

Hiding the complex implementation details and exposing only the essential features of an object.

Example: When you call the drive() method on a Car object, you don’t need to know how the method works internally.

Inheritance

Creating a new class that is a modified version of an existing class. The new class inherits attributes and methods from the parent class.

Example:

Polymorphism

The ability to present the same interface for different underlying data types or classes.

Example:

Tutorials dojo strip