Is Python an object-oriented programming language?
Python is a high-level programming language with various applications, such as web development, data analysis, machine learning, etc. It is a versatile language that supports multiple programming paradigms, some of which are given below:
Object-oriented programming (OOP)
Event-driven programming (EDP)
Functional programming (FP)
Aspect-oriented programming (AOP):
Procedural programming
Object-oriented programming (OOP)
OOP is a programming paradigm in which we can create objects and define the relationship between multiple objects. Objects are created through classes. A class defines different data variables and functions for an object.
The table below gives examples of some classes and the data it can contain:
Class | Variables | Sample Objects |
Song | name, genre, artist |
|
Employee | name, id, department |
|
Fruit | name, taste, origin |
|
The four fundamental concepts seen in OOP are abstraction, encapsulation, inheritance, and polymorphism.
OOP in Python
Python supports the OOP paradigm. We can create different classes, objects, and methods in it. It also supports all fundamental OOP concepts, such as inheritance, polymorphism, etc.
Code example 1
In Python, we use the keyword class to create a class. The following code shows how to create a simple class in Python:
# create a classclass song:def __init__(self, name, genre, artist):self.name = nameself.genre = genreself.artist = artist#create an objects1 = song("Animals", "Rock", "Maroon 5")#fetch attributes of the objectprint(s1.name)print(s1.genre)print(s1.artist)
Code explanation
Lines 2–6: We create a class
song.Lines 3–6: We define the
__init__function, which is called automatically when we create an object.Line 9: We create an object using the
songclass.
Code example 2
Now, let's create a function inside the song class that will update an object’s genre in the code given below:
# create a classclass song:def __init__(self, name, genre, artist):self.name = nameself.genre = genreself.artist = artistdef updateGenre(self, newGenre):self.genre = newGenre#create an objects1 = song("Animals", "Rock", "Maroon 5")#fetch attributes of the objectprint(s1.name)print(s1.genre)print(s1.artist)#call the update_genre functions1.updateGenre("Pop rock")#print the new genreprint('\nUpdated genre:')print(s1.genre)
Code explanation
Lines 2–8: We create a class
song.Lines 7–8: We define the
updateGenrefunction, which is called to update the genre of a song object.Line 11: We create an object using the
songclass.Line 19: We update the genre by calling the
updateGenrefunction.
Free Resources