Object-Oriented Programming in Python (Part 1): Classes and Objects

Object-Oriented Programming (OOP) is a programming model where programs are organized around objects and data rather than action and logic. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects.

Objects are created using classes, which are the focal point of Object-Oriented Programming. The class describes what an object will be, but it is separate from the object itself. In other words a class can be said to be the blueprint of of an object. It can also be used as a blueprint for creating multiple different objects.

Classes

Classes are created using the keyword class and an indented block which contains class methods (functions).

The code above defines a class name Cat, which has two attributes: color and legs. Then the class is used to create 3 separate objects of that class.

Methods

The __init__ method is the most important method in a class. This is called when an instance (object) of the class is created using the class name as a function.

All methods must have self as their first parameter, although it isn’t explicitly passed. Python adds the self argument to the list for you. You do not need to include it when you call the method within a method definition.

In an __init__ method, self.attributeName can therefore be used to set the initial value of an instance’s attribute.

Objects

Instances (objects) of a class have attributes which are pieces of data associated with them. In this example Cat instances have attributes color and legs, these can be accessed by putting a DOT and attribute name after an instance.

Result:

In the example above, the __init__ method takes two arguments and assigns them to the object’s attributes. The __init__ method is called the class constructor.

Classes can have methods defined to add functions to them. You have to remember that all methods must have self as their first parameter. These methods are accessed using the same DOT syntax as attributes.

Result:

Classes can also have class attributes created by assigning variables within the body of the class. These can be accessed either from instances of the class or the class itself.

Result:

Trying to access an attribute of an instance that isn’t defined causes an AttributeError. This also applies when you call an undefined method.

 

Result:

There are still more concepts of Object-Oriented Programming in Python that will be explored on in this series, like inheritance, magic methods, class and static methods, etc.

Related Posts