Object-Oriented Programming With Python
Python is a pure object-oriented high-level programming language. What do we mean by that? Everything we are using is an object. In another tutorial for file handling, we used a variable to store the file handler. After that, we can use various functions, e.g., read, write, etc., using a dot (.).
What does that mean? The file handler has all these functions. The open function returns the File class object, and the object’s reference is stored in the file handler.
In this tutorial, we will learn about the object-oriented capability in Python and how to create classes and objects with easy-to-understand examples.
What is a Class and an Object?
You can imagine a class is a blueprint for encapsulating information, and the object is the instance of a class for real use. When an object is created, the memory is allocated for storing data.
The class implements functions/methods to access/modify the data in objects. So we can say that data is private and methods are public.
For example, a person’s details are a class in the real world. That has a name, address, age, etc., as information and methods setName(), getName, setAddress(), getAddress(), etc, as methods to access/modify information.
What are the Access specifiers in Python?
The other object-oriented programming languages have access specifiers, private, public, and protected. Each specifier lets the user/programmer know who can access the code.
- Private (variable/functions) – Only the class members have access.
- Public (variable/functions) – Members can be accessed anywhere from the object.
- Protected – Can be accessed from class members or objects of the derived class (a class that inherits the class with protected members) only.
But in Python, there is only public, and there are conventions and other ways to make a member private or protected.
How to define a class and object in Python?
A class in Python can have data members and functions. The following example shows how to create a class and access its data members. The class declares two members and assigns integer values 1 and 2, respectively.
# Create a class
class MyFirstClass:
member_1 = 1;
member_2 = 2;
classObject = MyFirstClass(); #creating object
print(classObject.member_1); #printing first data member
print(classObject.member_2); #printing first data member
Output : py MyFirstClass.py 1 2
How to add a member function in a class? In the above print, we are printing members one by one. In the following example, we will show how we can add a function to the class for printing the data variables. Similarly, you can add any other function and implement the definition as you need.
# Create a class
class MyFirstClass:
member_1 = 1;
member_2 = 2;
def printMembers(self):
print(self.member_1);
print(self.member_2);
classObject = MyFirstClass(); #creating object
classObject.printMembers(); # Calling member function
Output: py MyFirstClass.py 1 2
What is self here? It is a reference to the object in question. Similar to this in java or C++. But there we can give it any name.
How do we initialize data members at the time of object creation? It is similar to the constructor in any other OOPs programming language. There is an _init_ function. Whenever a program creates an object, python calls, or that class can take multiple types of parameters as arguments.
# Create a class
class MyFirstClass:
# initialization function for members.
def __init__(self, input_1, input_2):
self.member_1 = input_1;
self.member_2 = input_2;
def printMembers(self):
print(self.member_1);
print(self.member_2);
classObject = MyFirstClass(5,6); #creating object
classObject.printMembers(); # Calling member function
Output: py MyFirstClass.py 5 6
How to set data members from a class method? The example has a function set(). A user program needs to call this function with arguments.
# Create a class
class MyFirstClass:
# initialization function for members.
def __init__(self, input_1, input_2):
self.member_1 = input_1;
self.member_2 = input_2;
def set(self, val1, val2):
self.member_1 = val1;
self.member_2 = val2;
def printMembers(self):
print(self.member_1);
print(self.member_2);
classObject = MyFirstClass(5,6); #creating object
classObject.printMembers(); # Calling member function
print("Setting new values 11,34");
classObject.set(11,34);
print("New values");
classObject.printMembers(); # Calling member function to print
Output- py MyFirstClass.py 5 6 Setting new values 11,34 New values 11 34
How to delete an object to free the memory?
When an object creates, the Python run time allocates memory. But it is always good practice to delete the object once it requires no anymore. The delete keyword frees the memory and avoids system crashes caused by the out-of-memory state. del is the keyword to delete an already created object. The following example is checking if an object exists, deleting, and again checking.
# Create a class
class MyFirstClass:
# initialization function for members.
def __init__(self, input_1, input_2):
self.member_1 = input_1;
self.member_2 = input_2;
classObject = MyFirstClass(5,6); #creating object
if classObject == None:
print("classObject not created ");
else:
print("classObject created ");
del classObject;
if classObject == None:
print("classObject not created ");
else:
print("classObject created ");
Output-
py MyFirstClass.py
classObject created
Traceback (most recent call last):
File "MyFirstClass.py", line 17, in
if classObject == None:
NameError: name 'classObject' is not defined
You can also delete individual data members of an object.
del classObject.member_1;
What is the pass keyword in Python?
The pass is a null or empty statement. When the interpreter reaches to pass, it does nothing and moves further. The pass is useful when creating a block with empty statements.
For example, if we want to create an empty class because we don’t know the exact functionality. Then we use a pass to add a line of code in class (as a class can not be empty). Similar is true for others, functions, loops, etc.
# Create a class
class MyFirstClass:
#Empty Class
pass;
classObject = MyFirstClass(); #creating object