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

Python

Example

Tutorials dojo strip
Python
  • 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

Python
  • 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.

Python

Example: demonstrates encapsulation by using a private attribute __balance inside an Account class. It also uses try, except, else, and finally blocks to safely handle withdrawals and exceptions like insufficient funds. The finally block ensures the balance is always printed, regardless of success or failure.

Abstraction

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

Python

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:

Python

Polymorphism

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

Example:

Python

Tutorials dojo strip