How To Write Python Classes: Code, Examples, & More
Python is an object-oriented programming (OOP) language.
OOP is methodology used by programmers that enables a system or program to be defined as a set of objects, which can be manipulated and controlled in a piece-by-piece manner.
It is important for you to understand why object oriented languages are necessary in programming. When creating complex code, object-oriented programming allows you to re-use code, making it easy to maintain and scale. It also puts emphasis on objects, unlike procedure oriented programming languages that stress the importance of functions.
In this article, I am going to teach you how to write Python classes - which are special constructs that programmers use to organize related items in an application.
What is a Python Class Object?
For you to understand Python classes, you will first need to understand what an object is.
In Python, an object is an encapsulation of variables and functions into a single entity. The object’s functions act on the data stored within the object. An object is also referred to as an instance. And hence, instantiation is the word we use to refer to the process of creating an object.
A class object is created with the same name as the class. We will see this in examples later in this article.
What are Python Classes?
A class is a code template used to create objects. On the other hand, objects are instances of classes.
An example could be helpful here. Consider a company that employs salespeople where one of these salespeople is named ‘Nick’.
If we needed to write this logic into a Python program, we would say that “Salesperson” is a class, while “Nick” is an instance of “Salesperson”. Each Salesperson instance has certain data associated with it (monthly sales, perhaps) and functions that it can perform (cold calling, as an example).
As you may have noticed, a class is different from a function in that it contains not just functions, but also data (stored in variables).
These data variables are referred to as properties. The functions are referred to as methods. A Python class is a blueprint for creating objects. Methods are functions that are defined inside a given python class.
To understand what a class is, let’s consider another example. You can think of a class as the design (or prototype) of a building. The design contains every detail about the building including material, size, and shape. Based on this description, the building is the object.
We can actually create many different buildings using the same blueprint. Each building would be an instance of the blueprint. These would have the same functions (or methods) within them (turn off the heat, perhaps), but would have different variables (location, as an example).
How To Define Python Classes?
In Python, a class is created using the keyword class, followed by the name of your class, as follows:
Python classes are somewhat unique because their first letter is always capitalized. So we would use Class_Name, not class_name or something similar.
Next, let’s consider the generalized layout of a Python class:
As you can see, a Python class consists of a list of statements, indented like a loop or a function. We are going to see an example of these statements in an actual class later on in this article.
Specifically, we will be creating a class called ‘Food’ for the remainder of this article.
classFood#More code will go here
Let’s add some attributes to this class next.
Class Attributes in Python
As we continue, you will notice that you can create a class without any arguments. However, a class by itself - without some functionality associated with it - is of no use.
Functionalities in Python classes are defined by setting attributes.
These attributes are variables that will contain data. As we mentioned earlier, data in a class are called properties.
Note that class attributes are attributes that are defined at the class level. These attributes are owned by class itself and will be shared by all the instances of that class.
Because they should have the same value for every instance. we define class attributes outside of the class methods (but still within the class object). In general class attributes are are placed at the top, just below the class header.
To understand these terms well, let’s set some attributes in the class we had created, class Food.
classFood:name='pizza'type='snack'#name and type set as attributes of the class Food
To summarize, class attributes are the same for all instances of the class, while class properties may differ between instances and can be modified by the class’s methods.
How To Instantiate Python Classes
Python classes can be assigned to variables. Assigning a class to a variable is what is called instantiation.
As I mentioned above, a class object is created with the same name as the class.
Once you instantiate your class, you then assign it to a variable. In our case, we shall instantiate the class Food and assign it to a variable called food.
food=Food()# instantiate the class Food and assign it to variable food
Accessing Class Attributes
Instantiating a class allows us to access the attributes defined in that particular class.
To access the attributes inside a class, we use the dot operator ..
For instance, let us consider our example class Food. Recall that it has two attributes, name and type:
We are going to access the attribute name using the following syntax.
print(food.name)#access the class attribute _name_ inside the class Food.
This will output the name of the food as shown below.
Similarly, we can access the type attribute as follows:
print(food.type)#access the class attribute name inside the class Food.
This will output the name of the food as shown below.
You should note that the class object not only allows us to access the attributes in that particular class, but also allows us to instantiate new objects of that class.
Methods in Python Classes
We have already seen how to define a python class and how to set some attributes in our class. We have also seen how to instantiate a class as well as how to access an attribute inside the class.
We will now see how methods in a class are defined.
How To Define Methods in a Python Class
Recall we said that a class contains two components: properties and methods.
In python classes, methods are functions that you define to access and/or modify the attributes.
It is important to note that once we define methods, we will always need to provide the first argument to the method with a self keyword.
For instance, in our example class Food, which has two attributes name _and _type, we can define one method, change_type. The defined method will take in an argument new_type along with the key-word self, as shown in the following code block.
classFood:name='pizza'type='snack'defchange_type(self,new_type)#note that the first argument is self
self.type=new_type#access class attribute _type_ with the self keyword
There is a lot to unpack here, so let’s discuss this example in a bit more detail.
You may have noticed the self-parameter in method definition inside the class. The self-parameter is a reference to the current instance of the class.
It is important to note that whenever an object calls its function, the object itself is passed as the first argument. Therefore, the first argument of the function in class must be the object itself. This is conventionally called self, although you could name it whatever you want.
The self parameter is used to access variables that belong to the class. You do not give a value for this parameter when you call the method. Instead, Python provides it.
Interestingly enough, if we have a method that takes no arguments, the requirement of the self parameter means that we still need to have one argument (self).
The following code block shows the instantiation of the Food class, and the modification of its type variable with the change_type method.
# instantiate the class
food=Food()# print the current object type
print(food.type)# This will output "snack"
#change the type using the change_type method
food.change_type("meal")print(food.type)#This will output “meal”
The _init _ Method
To have an understanding of Python classes, you need to understand the built in init method.
What is an _init_method?
The init method is found in all classes and is executed every time the class is initiated. The method is used to initialize the object’s state.
Let’s use our example class to see how this is done.
In this article, I have taken you through a comprehensive lesson in Python classes. We have learnt various aspects of Python classes from introduction to inheritance. If you’d like to work through some practice problems on Python classes, visit this page.