Search for Hubs, Articles and Topics
Search for Hubs, Articles and Topics

Class in Python: What is Python Class?

Learn about Class in Python.

21 Sep 2021-7 mins read

We always want similar things to be in the same place, just like we arrange the bookshelf at our home. We try to keep the books of the same genre under the same shelf. This way we divide the shelf according to the type of books we want to store.

In the same way in Python, we have classes to help us bring all the related objects and functionality together so that it helps us to manage our code in an easy manner.

Unlike other programming languages, Python revolves around the concept of objects. Hence, it is an Object-Oriented Programming Language(OOPs).

Classes and objects are two main aspects of OOPs.

Classes are the user-defined blueprints that help us create an object. Objects are the instances of a particular class. Every other element in Python will be an object of some class, such as the string, dictionary, number(20,30), etc will be an object of some corresponding built-in class(int, str) in Python.

Let’s take an example to understand this concept better.

Here, we have the blueprint of a car on the left side. This is known as the class while on the right side we have some of the models of the cars based on that blueprint, which are known as the objects of the particular class.

Refer to the following image below:

class in python

Creating a Class in Python

Creating a class is as easy as creating a function in Python. In function, we start with the “def” keyword while class definitions begin with the keyword “class”.

Following the keyword class we have the class identifier(i.e. the name of the class we created) and then the: (colon) operator after the class name.

In the next indented lines(statement 1..n) are the members of the class. Also, the variables inside the class are known as attributes. The attributes can be accessed later on in the program using the dot(.) operator.

The syntax for creating a Class in Python is as follows:

class ClassName:
    # Statement 1
    # Statement 2
    .
    .
    # Statement n

Let’s take a simple example of a class named “Scaler”.

class Scaler:
    pass

Note: The keyword pass denotes an empty class. It is written just to avoid any errors in the console while running the above code.

Python Class Attributes and Methods

To make the most of Python Classes, we also need to add some functionality to the classes. We can make this possible with the help of attributes and methods.

We need to set some attributes which would contain some functions and data. These would add some functionality to our code.

Those functions which we define inside the class are known as methods.

Let’s take a look at these additional functionalities in brief.

Python Class Attributes

These are the variables that are defined inside the particular class and can be used by all the objects. These attributes can, later on, be called by using the class and attribute name with the

dot(.) operator.

Let’s take a look at an example for further understanding.

class Scaler:
    Course = 'Python'

Here we have a class named “Scaler”, having a class attribute named “Course” which has a fixed value (ie ‘Python’).

Note: The value of any attributes will remain the same for all objects until and unless it is changed explicitly later on in the code.

Let’s continue with the above example to define some attributes and access it.

class Scaler:
    Course1 = 'Python'
    Course2 = 'C++'
    Course3 = 'Java'
# Accessing the values of the attributes
print(Scaler.Course1)
print(Scaler.Course3)
# Accessing through object instantiation.
obj= Scaler()
print(obj.Course2)

Output:

Python
Java
C++

Here we have defined several attributes inside the “Scaler” Class. Also, we have shown two ways of accessing the values of those attributes. One, by directly using class name and the other through using an object(class instance). Assigning a class to a variable is known as object instantiation.

Note: If we change the value of the attribute using the class name(the first method in the above example), then it would change across all the instances of that class. While if we change the value of an attribute using class instance(object instantiation), it would only change the value of the attribute in that instance only.

Let’s show an example to have clarity on this concept:

class Scaler:
    Course = 'Python'
# Changing value using Class Name
Scaler.Course = 'Machine Learning'
obj= Scaler()
print(obj.Course)
# Changing value using Class Instance 
obj.Course = 'AI'
print(obj.Course)   # Value will change in this instance only
print('Using class instance wont reflect the changes to other instances')
print(Scaler.Course) # Value haven't changed
obj2= Scaler()
print(obj2.Course)   # Value haven't changed

Output:

Machine Learning
AI
Using class instance wont reflect the changes to other instances 
Machine Learning
Machine Learning

Python Class Methods

Once we have defined the class attributes, we can even define some functions inside the particular class that can access the class attribute and can add more functionality to the existing code.

These defined functions inside a class are known as methods. We can define as many methods as we want inside a single class.

Syntax:

We define a method(function) inside a class using the “def” keyword, followed by the method name. We then pass some arguments through the method.

Note: When we define a method it must at least pass a single parameter which is generally named as “self”. It refers to the current instance of the class.

We can call this parameter by any name, other than “self” if we want.

Let’s take a look at an example of the same.

class Scaler:
    def CourseDetails(self): 
        print('Course Information')

We can also pass other arguments inside the “CourseDetails” function if we want.

For example, let’s say we have a class “Scaler”, in which we have an attribute named “name” and a method named “CourseDetails”. The method would take the argument “name” along with self. We can also pass multiple arguments as per our requirements in the code.

class Scaler:
    name = 'Python'
    
    def CourseDetails(self, name): 
        self.name = name

Instance Attributes (_init_method) in Python:

We can also provide the values of the attributes, during the time of object creation. Instance attributes are attached to the instance of a class. Whenever a new object of the class is created this method is called.

This is done by defining the attributes under the “_init_method”. The init method is similar to the constructors as in other programming languages(C++, Java). Such a method contains statements that would be executed during the run time(time of object creation).

Let’s take an example to have more clarity on this particular method. This method begins with a double underscore(__).

class Scaler:
  # init method
  def __init__(self, name):
    self.name = name
  # normal method
  def CourseDetails(self):
    print('The name of this course is', self.name)
study1 = Scaler('Python')
study1.CourseDetails()
study2 = Scaler('Machine Learning')
study2.CourseDetails()

Output:

The name of this course is Python
The name of this course is Machine Learning

Note: We can define separate attribute values for different objects(study1, study2) of a class.

Python Class Properties

In Python, with the property() function inside the class, we can define some additional functionalities.

The property() function, just like Java and other languages, takes the set, get and delete methods as arguments and returns an object. These functionalities can be easily incorporated into the code with property() function.

Let’s look at an example to understand the property() function –

class Scaler:
    def __init__(self):
        self.__name='Python'
    def setCourseName(self, name):
        print(' "setCourseName()" is called here')
        self.__name=name
    def getCourseName(self):
        print(' "getCourseName()" is called here')
        return self.__name
    name=property(getCourseName, setCourseName)
obj = Scaler()
obj.name = "C++"
print(obj.name)

Output:

"setCourseName()" is called here
"getCourseName()" is called here
C++

Here the property(getCourseName, setCourseName) returns the property object and then assigns it to the parameter name.

Note: Using a property decorator (@property) is recommended, instead of the property() method, though both work well.

Conclusion

Learned a lot of functionalities of a Python Class in one go? Don’t worry, go through the examples of each variation to clear your concept well. All the concepts are aided by simple and easy-to-understand code snippets. This article elaborately describes the Class in Python, which is a concept of OOPs. Objects and Classes are quite important concepts in Python. Many of the popular softwares are based on this concept of OOPs.

Do try using Python classes and methods to improve your coding experience in Python and practice similar problems to understand the logic well.

I hope this blog solved your doubts and was informative.