Object-Oriented Programming (OOP) is a form of programming centered around objects: small units that combine data and code. Simula was the first OOP language created for the simulation of physical models. Using OOP, you can define classes that act as templates for objects of specific types.
The core elements of OOP are classes, objects, methods, and attributes. OOP uses these elements to achieve fundamental aims: encapsulation, abstraction, inheritance, and polymorphism.
Python has excellent support for object-oriented programming. If you’re wondering about OOP or how to use it in Python, read on for the details.
What Is Object-Oriented Programming in Python?
Python is a general-purpose programming language that supports object-oriented programming. Its central infrastructure aims at object and class-building applications or designing. Using OOP makes Python code cleaner and clearer. It also provides for easier maintenance and code reuse.
Here is an example to show you why to use OOP in Python.
jeans = [30, true, "Denim", 59]
In this example, jeans contain a list of values representing price, whether the item is on sale, its material, and cost. This is a non-OOP approach and causes some problems. For example, there is no explanation that jeans[0] refers to size. This is highly unintuitive compared to an OOP approach which would refer to a named field: jeans.size.
This example code isn’t very reusable since the behavior it relies on isn’t discoverable. Using OOP, you can create a class to avoid this problem.
How to Define a Class in Python
To create a class in Python, use the keyword “class” followed by your chosen name. Here’s an example defining a class named Myclass.
class MyClass:
x = 2
p1 = MyClass()
print(p1.x)
Let’s define a class, Pant, to represent various types of pants. This class will contain the size, on-sale status, material, and price. By default, it initializes those values to None.
class Pant:
# Define the properties and assign None value
size = None
onsale = None
material = None
price = None
How to Create an Object in Python
Now let’s initialize an object from the Pant class. First, we’ll define the initializer method which has the predefined name _init_. Once you define it, Python will automatically call this method whenever you create an object from that class.
Secondly, a particular self parameter will allow the initialize method to select a new object.
Finally, after defining the initializer, we’ll create an object named jeans, using the [objectName] = Pant() syntax.
class Pant:
# Define the initializer method
def __init__(self, size, onsale, material, price):
self.size = size
self.onsale = onsale
self.material = material
self.price = price
# Create an object of the Pant class and set each property to an appropriate value
jeans = Pant(11, False, "Denim", 81)
Use Attributes and Methods to Define Properties and Behaviors
Objects in Python can use two different types of attribute: class attributes and instance attributes.
Class attributes are variables or methods that all objects of that class share. In contrast, instance attributes are variables that are unique to each object—the instance of a class.
Let’s create an instance method to interact with object properties.
class Pant:
# Define the initializer method
def __init__(self, size, onsale, material, price):
self.size = size
self.onsale = onsale
self.material = material
self.price = price
# Instance method
def printinfo (self):
return f"This pair of pants is size {self.size}, made of {self.material}, and costs {self.price}"
# Instance method
def putonsale (self):
self.onsale = True
jeans = Pant(11, False, "Denim", 81)
print(jeans.printinfo())
jeans.putonsale()
print(jeans.onsale)
Here, the first method, printinfo(), uses all properties except onsale. The second method, putonsale(), sets the value of the onsale property. Note how both these instance methods use the keyword self. This refers to the particular object (or instance) used to invoke the method.
When we call putonsale(), this method uses the self parameter to change the value of that specific object. If you’d created another instance of Pant—leggings, for example—this call would not affect it. An instance property of one object is independent of any others.
How to Use Inheritance in Python
You can expand the above example by adding a subcategory of the Pant class. In object-oriented programming, this is known as inheritance. Expanding the class will define extra properties or methods that are not in the parent class.
Let’s define Leggings as a subclass and inherit it from Pant.
# Leggings is the child class to parent class Pant
class Leggings(Pant):
def __init__(self, size, onsale, material, price, elasticity):
# Inherit self, size, onsale, material, and price properties
Pant.__init__(self, size, onsale, material, price)
# Expand leggings to contain extra property, elasticity
self.elasticity = elasticity
# Override printinfo to reference "pair of leggings" rather than "pants"
def printinfo(self):
return f"This pair of leggings is size {self.size}, made of {self.material}, and costs {self.price}"
leggings = Leggings(11, False, "Leather", 42, True)
print(leggings.printinfo())
The new initializer method takes all the same properties as the Pant class and adds a unique elasticity property. You can extend a class to reuse existing functionality and reduce code length. If your Leggings class did not inherit from the Pant class, you would need to reproduce existing code, just for a small change. You’ll notice these benefits more when you work with larger and more complicated classes.
Check if an Object Inherits From a Class With isinstance()
The isinstance() function checks if an object is an instance of a specific class or any of its ancestor classes. If the object is of the given type, or a type that inherits from it, then the function returns True. Otherwise, it’ll return False.
# Dummy base class
class Pant:
None
# Dummy subclass that inherits from Pant
class Leggings(Pant):
None
pants = Pant()
leggings = Leggings()
print(isinstance(leggings, Pant))
print(isinstance(pants, Leggings))
Note that Python considers the leggings object, of type Leggings, an instance of Pant, the parent class of Leggings. But a pants object is not an instance of the Leggings class.
Python Is the Perfect Introduction to OOP
Python has gained popularity because of its simple and easy-to-understand syntax compared with other programming languages. The language was designed around object-oriented programming, so it’s a great tool to learn the paradigm. Most large tech companies make use of Python at some point in their technology stack, and the prospects look good for Python programmers.