8 min to read
Python - Classes - Basic
This article is a part of the Python - 101 series, you can access the full version of the series here:
-
Coding 101
-
Writing functions in Python
-
Control flows in Python
-
Errors and exceptions
-
Classes
- Basic (you are here!)
- Methods in classes
Welcome to the eleventh article of the Python - Coding 101 series, after reading this article, you will learn:
- What is classes and object-oriented programming
- 4 principles in object-oriented programming
- How to define a class in Python
- Why use classes and OOP
At this point you know how to use functions to organize code and built-in types to organize data. The next step is to learn “object-oriented programming”, which uses programmer-defined types to organize both code and data.
- 1. Classes and objects in Python
- 2. 4 Principles of OOP
- 3. Define a class in Python
- 4. Creating an Object in Python
- 5. Why should I bother using class instead of function in Python?
1. Classes and objects in Python
Python is an object oriented programming language. Unlike procedure oriented programming, where the main emphasis is on functions, object oriented programming stresses on objects. Almost everything in Python is an object, with its properties and methods.
An object is simply a collection of data (variables) and methods (functions) that act on those data. We can think of class as a blueprint, based on which we build the object that we desire. The difference between classes an objects can be found in the figure below:
2. 4 Principles of OOP
There are 4 principles that make up object-oriented programming:
-
Encapsulation
Encapsulation is the process of combining data and functions into a single unit called a class; it keeps data both safe from outside interference and misuse. With Encapsulation, the data is not accessed directly. It can only be accessed through public functions present inside the class called methods. Encapsulation is achieved by keeping it’s state private. Or in other words, encapsulation allows for us to create methods that can only be accessed or changed by public methods.
-
Abstraction
The main purpose of Abstraction is to handle the complexity of the program by hiding unnecessary detail from the user. This allows users to implement advance logic without having to understand or to think about all the hidden complexity.
-
Inheritance
Inheritance is the concept of having a class inherit from another class because it allows for code to be reused. In inheritance, the child class inherits the methods from the parent class. However, it is possible to modify a method in a child class that it has inherited from the parent class, which will be explained in Polymorphism.
-
Polymorphism
The word polymorphism means having many forms. In programming, polymorphism means same function name (but different signatures) being uses for different data types.
In Python, Polymorphism lets us redefine methods in the child class that have the same name as the methods in the parent class. This is particularly useful in cases where the method inherited from the parent class doesn’t quite fit the child class.
3. Define a class in Python
Like function definitions begin with the def keyword in Python, class definitions begin with a class keyword.
The first string inside the class is called docstring and has a brief description about the class. Although not mandatory, this is highly recommended.
Here is a simple class definition.
>>> class MyNewClass:
... '''This is a docstring. I have created a new class'''
... pass
A class creates a new local namespace where all its attributes are defined. Attributes may be data or functions.
There are also special attributes in it that begins with double underscores __
. For example, __doc__
gives us the docstring of that class.
As soon as we define a class, a new class object is created with the same name. This class object allows us to access the different attributes as well as to instantiate new objects of that class.
>>> class Person:
... "This is a person class"
... age = 10
>>> print(Person.age)
10
>>> print(Person.__doc__)
This is a person class
4. Creating an Object in Python
We saw that the class object could be used to access different attributes.
It can also be used to create new object instances (instantiation) of that class. The procedure to create an object is similar to a function call.
>>> aiden = Person()
This will create a new object instance named aiden
. We can access the attributes of objects using the object name prefix.
Attributes may be data or method. Methods of an object are corresponding functions of that class. This will be further discussed in the next article on classes in this 101 series.
This means to say, since Person.greet
is a function object (attribute of class), aiden.greet
will be a method object.
>>> class Person:
... "This is a person class"
... age = 10
...
... def greet(self):
... print('Hello')
>>> aiden = Person()
>>> print(Person.greet)
<function Person.greet>
>>> print(aiden.greet)
<bound method Person.greet of <__main__.Person object>>
>>> aiden.greet()
Hello
You may have noticed the self
parameter in function definition inside the class but we called the method simply as aiden.greet()
without any arguments. It still worked.
This is because, whenever an object calls its method, the object itself is passed as the first argument. So, aiden.greet()
translates into Person.greet(aiden)
.
In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.
For these reasons, the first argument of the function in class must be the object itself. This is conventionally called self
. It can be named otherwise but we highly recommend to follow the convention.
Now you must be familiar with class object, instance object, function object, method object and their differences.
5. Why should I bother using class instead of function in Python?
Non-OOP programs may be one long list of commands. More complex programs will group lists of commands into functions or subroutines each of which might perform a particular task. With designs of this sort, it is common for the program’s data to be accessible from any part of the program. As programs grow in size, allowing any function to modify any piece of data means that bugs can have wide-reaching effects.
In contrast, the object-oriented approach encourages the programmer to place data where it is not directly accessible by the rest of the program. Instead the data is accessed by calling specially written functions, commonly called methods, which are either bundled in with the data or inherited from “class objects” and act as the intermediaries for retrieving or modifying those data. The programming construct that combines data with a set of methods for accessing and managing those data is called an object.
TL;DR: the benefit of using classes can be summarized as follow
-
MAINTAINABILITY
Object-oriented programming methods make code more maintainable. Identifying the source of errors is easier because objects are self-contained.
-
REUSABILITY
Because objects contain both data and methods that act on data, objects can be thought of as self-contained black boxes. This feature makes it easy to reuse code in new systems.Messages provide a predefined interface to an object’s data and functionality. With this interface, an object can be used in any context.
-
SCALABILITY
Object-oriented programs are also scalable. As an object’s interface provides a road map for reusing the object in new software, and provides all the information needed to replace the object without affecting other code. This way aging code can be replaced with faster algorithms and newer technology.
Comments