PYTHON OBJECT ORIENTED PROGRAMMING
In this tutorial, you’ll find out about the Object Oriented Programming (OOP) in Python and its essential concept with examples.
Python is based on object oriented programming. Because of this, making and utilizing classes and its objects is pretty simple. This section encourages you become a specialist in utilizing Python’s object oriented concepts.
If you haven’t had any past involvement with Object Oriented Programming, you may want to go for some online introductory course or at least a short tutorial to have a grasp. But, if you you want to learn about Object Oriented particularly in Python then this tutorial is for you. Let’s go through the main concepts of OOP briefly:
Python Object Oriented Programming
Class
In order to understand a Class, we need to focus on an object first because an object is an instance (part) of a class. We have learned so far that Python includes data structures like: strings, lists numbers etc but what if we want to present something more complicated.
Let’s say that we want to represent information of school students. If you want to go according to the list then you would end up creating different lists like their names, ages, roll number subjects grades etc.
How would you know that which element is required for which student. Let’s say you have hundred students. How are going to make sure that all the students have name or age and so on? What if you want to add other attributes to the student information as well?
Classes are used to create a custom defined data structure that is going to cater the user’s need in order to obtain information about something. In case of a student information, we should create a Student() classes to include different characteristics of the student like name, age or subjects.
You must remember that a class is just a blueprint as is just provides the structure of how something should be defined, but it isn’t a real object itself. The Student() class may have the characteristics like name, age or subject but it will not declare any information regarding the attributes.
You may think of a class as an idea of origin for its instances.
Python Objects
While the class is the idea or blueprint structure, an instance is a real part of the class having actual values of the attributes of the class. It’s not a blueprint anymore, in case of our Student() class example, it’s object is an actual student who has a name like Smith who is 9 years old.
The example for object of Student class can be:
student_obj = Student()
Here, student_obj belongs (as an object) belongs to the Student() class.
Defining a Class in Python
The example of creating a class in Python is below:
class Student: pass
We have used the class keyword to define a sample Student class, from this class, we can construct objects. Here, we are using the pass keyword as a placeholder where the main code will go. Also, if you run the code with the pass statement, it won’t generate an error.
Instance Attributes
Classes will create objects, and all objects will have characteristics known as attributes which are also referred to as the properties (or behaviors) of objects. In order to specify the initial attributes we use an initializer ( __init__() ) method to initialize the object initial attributes. This method will contain the self variable which refers to the object itself.
Remember self is NOT a keyword in Python, it is just a convention. You can use any other parameter name instead of self. But since, self is a well known notation so it’s always in practice.
class Student: # Initializer / Object Attributes def __init__(self, name, age): self.name = name self.age = age
Class Attributes
Since instance attributes are specific to each object, class attributes are uniform for all instances.
class Student: #Class Attribute species = 'humans' # Initializer / Object Attributes def __init__(self, name, age): self.name = name self.age = age
While every student will have a unique name and age, but the commonality between them will be that they are humans.
Creating Objects
You can create an object derived from a class by simple equating an object to a class
#First object of Student class stu1 = Student("John", 16) #Second object of Student class stu2 = Student("Anna", 15)
Now that we have created two new objects. So, in order to relate an object to the class, we assigned two objects to the Student class and inside the parentheses ()
we have declared the two parameters which we have initially set as name and age.
Accessing Objects
Moving on, once we have created the objects’ it’s time to access them. In order to access the objects you have to connect them with the parameters mentioned as object attributes with dot notation.
print("Student's name is " + name + " and age is " + str(age))
We have converted the age (declared as number) parameter into a number since Python is going to generate an error if we are using it along with a string.
Creating Methods
You can create your own methods apart from the initializer method inside the body of the class where you can designate different behaviors of an object.
# instance methods def performance(self, grades): self.grades = grades print("The grade of student is: " + self.grades) stu1 = Student("John", 16) stu1.performance("A+")
Deleting Object in Python
If you don’t need an object anymore, you can always delete it by using the del command in Python.
del stu1 stu1
Output:
Traceback (most recent call last): File "C:\Users\Hira\Desktop\test.py", line 88, in print(stu1) NameError: name 'stu1' is not defined
Inheritance in OOP
You can create child classes in python which are derived from parent classes without modufying it. Let’s say that I have a class where I want to classify Girls and derive it from the Student class. So, I will create a new class now and refer it to my Student class. The main point of creating a child class is that you can inherit the current methods that are present in the parent class while creating new ones for your child class. For example:
class Student: #Class Attribute species = 'humans' # Initializer / Object Attributes def __init__(self, name, age): self.name = name self.age = age print("Student's name is " + name + " and age is " + str(age)) def performance(self, grades): self.grades = grades print("The grade of student is: " + grades) class Girl(Student): def __init__(self, name, age): super().__init__(name, age) print("Girl class is ready") def whichclass(self): print("This is Girls class which is a child class of Student class.") stu1 = Student("John", 16) stu1.performance("A+") stu2 = Student("Smith", 24) stu2.performance("B") print("\n") girl1 = Girl("Anna", 21) girl1.whichclass() girl1.performance("B")
In the above example, we have two classes i.e. the Student(parent) class and the other is the Girl (child class). The Girl class will inherit the functions of parent class. We can understand that the Girl class is also using the performance() method. We can also see that while having parent class methods and attributes, Girl class also has its own method: ‘whichclass’.
Furthermore, we are using a super() function before the initializing method; this is because we want to get the content of __init__ method from the Student class (parent class) into the Girl class (child class).