Python classes examples explained [Beginners]

Related Searches: python class, python object, python class example, python create class, python define class, python class object, python create object, python3 class, classes and objects in python, python class definition, python instantiate class, python class tutorial, python class in class, python instance, python class function, tutorial class, python classes explained, how to create a class in python, what is an object in python, making a class in python, class def, python class syntax, create class, how to use classes in python, python new object, class function python, how to make a class in python, python class declaration, python new, python class structure, writing a class in python, python create new object, python class instance, python new class, using classes in python, how to define a class in python, how to call a class in python, python class object parameter, how to create an object in python, python create instance of class, python class object vs class, how to write a class in python, what is a class method in python, python using classes, when to use classes in python, python classes and objects exercises, python make, python class method example, python when to use classes

 

Introduction to a python class

We all know that Python is an Object-Oriented Programming Language which means that Python implements a programming paradigm based on objects, where every object can store some data and code which can be modified. Class is a description of the object. Python class defines attributes that characterize the object and the methods that the object implements. In this tutorial, we will cover python classes, syntax and constructors. We will also cover python inheritance and polymorphism along with examples. By the end of this tutorial you will have a strong command over Python classes.

Advertisement

 

Getting started with python class

Python class is the best way to describe the data and functionality of an object. In simple words, the Python class is a programmatic way of describing the world around us. For example, we might have a class of a house with different attributes like rooms, size, location, and many more.

Creating a new class in Python allows us to create a new type of object. A user-defined class contains different methods which can be used to manage data and describe the object. In this section, we will describe the basics of python classes.

 

Definition and syntax of a python class

In Python, we use the keyword class to create a new class. All the statements and methods go inside the class. See the simple syntax of the python class below:

class Name_of_Class:
   <methods and statements of class>

It is always best practice to have a docstring before the methods and variables to describe the purpose of the class. A docstring is written inside triple single (‘’’) or double (“””) quotes. See the syntax below along with docstring.

class Name_of_Class:
   '''This is example of python class'''
   <methods and statements of class>

In python double underscore(__) methods and attributes are special methods which have special meaning and uses. For example __doc__, __init__(). The __doc__ is used to print the docstring of python class. See the example below:

class Name_of_Class:
   '''This is example of python class'''
   # <methods and statements of class>

# printing docstring
print(Name_of_Class.__doc__)

Output:

Advertisement
This is example of python class

 

Python class vs instance variable

In python we come across two different types of attributes available in Python; A class attribute and an instance attribute. A class attribute is a python variable that belongs to a class itself rather than a particular object. It is defined outside the constructor function and is available to all the objects of class. While an instance attribute is a Python variable that belongs to one object only. This variable is defined inside a constructor function and is only accessible in the scope of that particular object only.  See the example below which uses  both of the variables.

# python class
class University:
   # class attribute
   Room_numbers = 1000 
  
  # constructor
   def __init__(self, name_of_uni):

       # instance variable
       self.name = name_of_uni

Here, room_number is a class attribute while name_of_uni is an instance variable.

 

Attribute referencing in Python

Attribute referencing in python classes is the same syntax as the standard syntax used by all attribute references in Python. For example, class_object.name is an attribute reference. See the following example of attribute referencing in Python.

# python class
class University:

   # class attribute
   Room_numbers = 100
   dean_name = "Mr Maxwell"

# printing class attribute
print(University.Room_numbers)
print(University.dean_name)

Output:

100
Mr Maxwell

Notice that in the above example we didn't create a new object, we directly used the class name and got access to the class attributes.  However, we can also create new classes of type University and get access to the class attributes. See the example below:

# python class
class University:

   # class attribute
   Room_numbers = 100
   dean_name = "Mr Maxwell"

# creating object of university
main_campus_one = University
main_campus_two = University

# printing class attribute
print(main_campus_one.Room_numbers)
print(main_campus_two.dean_name)

Output:

100
Mr Maxwell

 

Constructors in Python

We already discussed that class methods that begin with a double underscore are of special type and have special meaning. One of those special methods which start with a double underscore is __init__(). This special function is called and executes whenever a new object of the class is initiated and is called a constructor of the class. Now let us take a simple example and see how the syntax of a python constructor looks like.

# python class
class University:

   # Python constructor
   def __init__(self, rooms, dean_name):
       self.rooms = rooms
       self.dean_name = dean_name

In the above syntax of constructor, notice there is an argument named self. This is always the very first argument of a constructor or any other method of a class. It actually references the instance of the class and always points to the current object. We can get access to any class instance or method using selt. Now let us take an example, create an object of type university and get access to instance attributes using self. See the example below:

Advertisement
# python class
class University: 

   # Python constructor
   def __init__(self, rooms, uni_name):
       self.rooms = rooms
       self.uni_name = uni_name

   def Intro(self):
       print("Welcome to the {}".format(self.uni_name))

# creating object of type University
universtiy1 = University(100, "University of central asia")
universtiy2 = University(150, "All Indian University")

# getting access to instance attributes
universtiy1.Intro()
universtiy2.Intro()

Output:

Welcome to the University of central asia
Welcome to the All Indian University

Notice that in the above example, first we created two objects of type University and then got access to the names of the objects using the self keyword.

 

Methods in Python class

We already have touched methods in python in our previous section, but here we will get into them and explicitly define them. In Python, a class method is simply a function that is defined within the scope of the class. For example, the function Intro() in the previous example was a class method. See the following example of methods in the python class.

# python class
class University:

   # method in python
   def sayHello(self):
       return "Hello from out University"

sayHello() in the above example is a method. Simply a function inside the scope of the class is known as a method.

 

Deleting and modifying a class attribute

As we can easily get access to the class attributes, it is very easy to change or modify them as well. We just need to get access and then change the property or class attribute by setting its value to other values. See the example below of how we changed the name of the university.

# python class
class University:

   # class attributes
   name_of_uni = "UCA"

# create object type of University
Uni = University

# printing actual Value
print(Uni.name_of_uni)

# changing the class attribute
Uni.name_of_uni = "university of central asia"

# printing the changed attribute
print(Uni.name_of_uni)

Output:

UCA
university of central asia

Notice that in the example above we changed the class attribute using the syntax obj_name.class_attribute and set its value.

In a similar way we can also delete the class attribute, but this time we have to use the keyword del to delete the attribute of the class.  See the same example where we will delete the name of a university using keyword del and when we try to get access to the deleted attribute we will get an error.

Advertisement
# python class
class University:

   # class attributes
   name_of_uni = "UCA"

# create object type of University
Uni = University

# printing before deleting
print(Uni.name_of_uni)

# deleting the name
del Uni.name_of_uni

# printing after deleting
print(Uni.name_of_uni)

Output:

Python class examples explained [Beginners]

Notice that we get the error that says we don't have any attribute with that name, it is because we deleted the attribute

 

Getting start with Python inheritance

Python inheritance is another very important feature of a Python class in which it inherits/takes all the properties, methods, and attributes from another class. Inheritance is simply talking about the parent class that shares its attributes and methods with another class known as the child class. Inheritance is very important and useful when we need to extend the behavior of the base class without copy-pasting the code completely. In this section, we will cover the basic syntax of python inheritance along with taking examples.

 

Child class and parent class syntax

The syntax of child and parent classes is very simple. See the following simple syntax of python inheritance.

# python parent class
class University:

   # class attributes
   name_of_uni = "UCA"

# python child class
class main_campus(University):
   # method inside child class
   def name(self):
       return self.name_of_uni

In this simple syntax, class University is the parent class and class main_campus is the child class. Notice that the child class takes the parent class inside brackets which means it will have access to all the attributes and methods of the parent class. Now let us print the name of the university using its child class. See the example below:

# python parent class
class University:

   # class attributes
   name_of_uni = "UCA"

# python child class
class main_campus(University):

   # method inside child class
   def name(self):
       return self.name_of_uni

uni = main_campus()
print(uni.name())

Output:

UCA

Notice that we didn't create an object of type University, we just created object type main_campus but it inherits the name of class University. That is how inheritance works

 

 

Overriding base class in Python

As we know, python inheritance inherits all the attributes and methods of the parent class. Sometimes we might don't want exact similar attributes and we might want to change their properties. We can always redefine inherited attributes and functions in a child class. See the following example where we will change the name of the university in the child class.

# python parent class
class University:

   # class attributes
   name_of_uni = "UCA"

# python child class
class main_campus(University):
   name_of_uni = "University of central asia"

   # method inside child class
   def name(self):
       return self.name_of_uni

uni = main_campus()
print(uni.name())

Output:

University of central asia

In a similar way we can also change the output of a method by redefining the method in child class. See the following example which overrides the method in child class.

# python parent class
class University:

   # introduction
   def intro(self):
       print("Hello from University")

# python child class
class main_campus(University):

   # overriding the method
   def intro(self):
      print("welcome to UCA")

uni = main_campus()
uni.intro()

Output:

welcome to UCA

Notice that the output is welcome to UCA instead of Hello from university because the child class overrides the parent class’s method.

 

Multiple inheritance in Python

So far, we have seen how we can inherit the functionalities of one parent class inside a child class through inheritance. One of the important features of python inheritance is the multiple inheritance where we can inherit the properties from more than one parent class in a single child class without writing the code again. It is similar to single inheritance which is a difference that this time instead of one parent there will be more parent classes. See the example below:

# python parent class 1
class University:

   # introduction
   def intro(self):
       print("Hello from University")

# python parent  class 2
class main_campus:

   # welcome
   def welcome(self):
       print("Welcome to UCA")

# child class
class myUniversity(University, main_campus):
   def about(self):
       print("one of the best universities")

# creating object
uni = myUniversity()
# inherit from parent class
uni.intro()
# inherit from parent class
uni.welcome()
uni.about()

Output:

Hello from University
Welcome to UCA
one of the best universities

 

Hierarchical inheritance in Python

The difference between multiple inheritance and hierarchical inheritance is that in multiple inheritance one child inherits properties from more than one parent class while in hierarchical inheritance, multiple childs inherit the properties from a single parent. See the example below, where two child classes inherit properties from a single parent class.

# python parent class 1
class University:

   # introduction
   def intro():
       print("Hello from University")

# python child class 1
class main_campus1(University):

   # welcome
   def welcome():
       print("Welcome to UCA")

# python child class 2
class main_campus2(University):
   # location
   def location():
       print("it is located in Tajikistan")

# child one
child1 = main_campus1
child1.intro()
child1.welcome()
# child two
child2 = main_campus2
child2.intro()
child2.location()

Output:

Hello from University
Welcome to UCA
Hello from University
it is located in Tajikistan

 

Polymorphism in Python class

In general, the word polymorphism means multiple or more than one form. In programming, polymorphism means defining the same function but with different parameters each time. Python will automatically detect which function to use based on the provided arguments. For example len() is a built-in function which can count the elements in a list or the characters in the string. Likewise, python polymorphism allows us to define the same function in each class and get access to them based on the class type.  See the example below which will clear everything about python polymorphism.

# python class
class University:

   # introduction
   def intro():
       print("Hello from University")
       # hello function
   def hello():
       print("Hello! from main campus")

# python class
class main_campus:

   # Introduction
   def intro():
       print("Welcome to UCA")

       # hello function
   def hello():
       print("main campus!")

# creating objects
intro = University
Hello = main_campus
 
# for loop to iterate
for i in (intro, Hello):
   i.intro()
   i.hello()

Output:

Hello from University
Hello! from main campus
Welcome to UCA
main campus!

Here in the above example notice that python uses two different class types in the same way. We created a for loop that iterates through a tuple of objects.

 

Encapsulation in Python

Another important feature of python classes or object-oriented programming is the concept of encapsulation through which we can restrict the access to methods and variables of the class. In this section, we will discuss the protected class data in python and will explain it through solving an example.

 

Protected class data in Python

We know that an object’s attribute may or may not be visible outside of the class scope or definition. In Python we use the double underscore (__) method to hide or protect base class variables or functions to access from the child class.  See the example below which protects the variable.

# python class
class University:

   # protected variable
   __rooms = 100
   teachers = 30
   # Updating class variable
   def updateTeachers(self):
       # addes 10 to teachers
       self.teachers+=10
       return self.teachers

   # updating class variable
   def updateRooms(self):

       # adds 20 to rooms
       self.__rooms+=20
       return self.__rooms
myUni = University()

# getting access to the class variables
print(myUni.teachers)
print(myUni.__rooms)

Output:

Python class examples explained [Beginners]

 

Notice in the example that we get access to variable teachers but can get access to __rooms because __rooms is protected data. We can only get access to it through the method. See the example below:

# python class
class University:

   # protected variable
   __rooms = 100
   teachers = 30

   # Updating class variable
   def updateTeachers(self):
       # addes 10 to teachers
       self.teachers+=10
       return self.teachers

   # updating class variable
   def updateRooms(self):

       # adds 20 to rooms
       self.__rooms+=20
       return self.__rooms
myUni = University()

# getting access to class variable through method
print(myUni.updateTeachers())
print(myUni.updateRooms())

Output:

40
120

 

Summary

Python is an object-oriented programming language and almost everything in python is an object with its own properties and methods. A class is like an object constructor or a kind of blueprint for creating objects. In this tutorial we learned almost everything about classes. We covered python classes, constructors, class attributes, deleting and modifying attributes by taking different examples. We also learned about python inheritance, we discussed single and multiple inheritance by taking examples. Moreover, we also covered polymorphism and python encapsulation methods as well.

 

Further Reading Section

Python class
Python class documentation
More about Objects 

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment