In this chapter, you will learn to create repeatable and organized code using classes and objects in Python.
What are classes and objects?
Since Python is an object-oriented programming language, it focuses on entities known as ‘objects’.
An object is a collection of data and methods (functions) and in order to create such objects, we need to create a class in Python.
The class acts as a blueprint for the object and it also allows us to create multiple instances of the object type. Each class instance can have attributes and methods to maintain and modify its state, respectively.
Why should you use classes and objects in Python?
Most senior-level Python programmers have the habit of creating classes and objects for different functions of their code and they have a very good reason to do so. Let us understand this with an example.
Consider that you are working as a Python programmer in a car company. The company manafactures 10 different models of car and the manager has asked you to create a programmatical script that represents each model of the car.
In this case, you can create a single class that holds the basic properties of each car model such as the number of tires a car has, the number of seats in the car, etc. Then, you can easily inherit the property of the class ‘Car’ for each model of the ‘Car’. This is considered as good coding practices since you are writing DRY (Don’t Repeat Yourself) code.
On the other hand, if you were not using object oriented programming, you would have to define 10 different functions containing the same lines of code in each of them for the base features of the car.
How to create classes and objects in Python?
In Python, a class can be defined by using the keyword class. The simplest form of class definition looks like this:
# Creating a class in Python class ClassName: <statement1> ............ <statementN>
The following example illustrates a class that has an attribute (variable) x and a method (function) demoMethod:
class DemoClass: # Attribute x = 0 # Method def demoMethod(self): print('Method successfully called')
Objects can be instantiated from an already defined class. The general syntax for creating an object from a class is as follows:
objectName = ClassName()
The following example demonstrates how you can instantiate an object from the DemoClass created earlier. Then, you can access the attribute (x) as well as call the method demoMethod from the object.
# Instantiating an object >>> obj1 = DemoClass() # Accessing the attribute >>> print(obj1.x) 0 # Calling the method (function) >>> obj1.demoMethod() 'Method successfully called'
The __init__() method in Python
All classes create objects, and all objects contain characteristics called attributes.
We use the __init__() method to initialize (specify) the initial attributes of an object by giving them their default value (or state). These values are automatically initialized when an object is instantiated from a class.
The following example illustrates the use of the __init__() method:
# Simple class implementation in Python class MyClass(object): # Example of an init method def __init__(self, val): # Value initialization self.value = val # Example of a user-defined method def value_show(self): print("The value of my class is", self.value) my_class_object1 = MyClass(365) my_class_object2 = MyClass(48) my_class_object1.value_show() my_class_object2.value_show() # Printing the address of the object print(my_class_object1)
OUTPUT: The value of my class is 365 The value of my class is 48 <__main__.Myclass object at 0x000001F0C57050F0>
From the above example, we can also see that the value of attributes differs for each object in a class. In other words, each object has its own values of the attributes specified in the class definition.
Scopes and Namespaces in Python
Scope refers to the coding region from which a particular Python object is accessible. A namespace is a system that ensures that each and every Python object has a unique name. The following example illustrates this:
# An example of Scopes and Namespaces def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam spam = "nonlocal spam" def do_global(): global spam spam = "global spam" spam = "test spam" do_local() print("After local assignment:", spam) do_nonlocal() print("After nonlocal assignment:", spam) do_global() print("After global assignment:", spam) scope_test() print("In global scope:", spam)
OUTPUT: After local assignment: test spam After nonlocal assignment: nonlocal spam After global assignment: nonlocal spam In global scope: global spam
Inheritance in Python
When a class inherits attributes and methods of another class, then, this is known as inheritance in Python.
This means that we can create a new class from an existing class by inheriting the existing class’s attributes as well as methods. This follows the principle of writing DRY code and we are able to quickly create new classes from existing ones.
The syntax for inheritance in Python is as follows:
class BaseClass: Attributes and methods of BaseClass class DerivedClass(BaseClass): Attributes and methods of DerivedClass
As we can see in the syntax above, a derived class can inherit the attributes and methods of the base class (also known as parent class) by passing the base class as a parameter of the derived class.
Multiple inheritance in Python
When a derived class inherits attributes and methods from multiple parent classes, it is called as multiple inheritance in Python.
In the syntax given below, t
he derived class (
DerivedClass) is inheriting the attributes and methods from multiple base classes given by
class BaseClass1: Attributes and methods of BaseClass1 class BaseClass2: Attributes and methods of BaseClass2 ... class BaseClassN: Attributes and methods of BaseClassN class DerivedClass(BaseClass1, BaseClass2, ..., BaseClassN): Attributes and methods of DerivedClass
Multi-level inheritance in Python
When a derived class inherits attributes and methods from another derived class, then, this is known as multi-level inheritance in Python.
In the syntax given below, t
he derived class (
DerivedClass2) is inheriting the attributes and methods from another derived class (
DerivedClass1) which is also inheriting a base class (
class BaseClass: Attributes and methods of BaseClass1 class DerivedClass1(BaseClass): Attributes and methods of DerivedClass1 class DerivedClass2(DerivedClass1): Attributes and methods of DerivedClass2
You are now familiar with one of the most important topics in Python programming, that is, the concept of Classes and Objects in Python. In the next chapter, we will introduce the ‘Standard libraries used in Python‘, along with their uses.