What is a Class in OOP and How to Create and Use Them in Python?

Learn about the core functionality of Python classes, and how to create and use them in your program.

Picture of Nsikak Imoh, author of Macsika Blog
The text What is a Class in OOP and How to Create and Use Them in Python? on a white background image
The text What is a Class in OOP and How to Create and Use Them in Python? on a white background image

This post is part of the tutorial series titled Learn the various concepts of object oriented programming in Python

Table of Content

Object-oriented programming language stresses the use of classes and objects to structure codes unlike procedure-oriented programming, where the main emphasis is on functions

Python is an object-oriented programming language, as a result, almost all the code is implemented using a special construct called a class.

As a matter of fact, the primitive data types in Python are regarded as classes.

A class is a code template for creating another construct called an object.

In this lesson, you will learn about the core functionality of Python classes, and how to create and use them in your program.

What is a Class in OOP?

A class is a blueprint or prototype from which objects are created.

Classes provide a means of bundling data and functionality together.

Creating a new class allows new instances of that class to be made.

Each class has attributes and states, and the class instance uses those attributes attached to it for maintaining and modifying its state.

A class uses methods for maintaining and modifying its state.

What is a Class in Python?

A class in Python is a collection of instance and class variables and their related methods that define a particular object type.

Attributes are the names given to the variables that make up a class.

A class instance with a defined set of properties is called an object.

For example, If we design a class based on the states and behaviors of a Person, then States can be represented as instance variables and behaviors as class methods.

As a result, the same class can be used to construct as many objects as needed.

What is the Importance of Classes in OOP?

To understand the need for creating a class in Python let's consider an example, let's say you wanted to track the number of cars that may have different attributes like color and engine type.

If a list is used, the first element could be the car's color, while the second element could represent its age.

Let's suppose there are 100 different cars, then how would you know which element is supposed to be which?

What if you wanted to add other properties to these cars?

A solution like the aforementioned lacks proper code structure, and that's the exact need for classes.

How to Create a Class in Python

In Python, a class is defined using the class keyword. The syntax to create a class is given below.

class ClassName:
      '''This is a docstring. '''
      <statement 1>
      <statement 2>
      .
      .
      <statement N>
  
Highlighted code sample.
  • ClassName: It is the name of the class
  • Docstring: This is an optional requirement used to give an elaborate description of the class and how to use it.
  • statements: These represent the various attributes and methods of the class.

In this example, we are creating a Car class with model, brand, and color instance variables.

class Car:
    # class variable
    speed_measurement = "KM/hr"
  
      def __init__(self, model, brand, color):
          # data members (instance variables)
          self.model = model
          self.brand = brand
          self.color = color
  
      # Behavior (instance methods)
      def info(self):
          print('Model:', self.model, 'Brand:', self.brand, 'Color:', self.color)
  
Highlighted code sample.

What are the Attributes of a Class in Python?

When we design a class in Python, we use instance variables and class variables.

In a class, attributes can be defined in two parts:

1. Instance variables: The instance variables are attributes attached to an instance of a class.

We define instance variables in the constructor i.e. the __init__() method of a class.

In our example above, the instance variables are self.model, self.brand, and self.color.

The instances of a class do not share instance attributes. Instead, every instance has its copy of the instance attribute and is unique to each.

2. Class Variables: A class variable is a variable that is declared inside of the class, but outside of any instance method or __init__() method.

In our example above, the class variable is speed_measurement.

All instances of a class share the class variables. However, unlike instance variables, the value of a class variable is not varied from instance to instance.

Only one copy of the static variable will be created and shared between all instances of the class.

The difference between instance and class variables is that:

Instance variables are for data, unique to each instance, and class variables are for attributes and methods shared by all instances of the class.

Instance variables are variables whose value is assigned inside a constructor or instance method, whereas class variables are variables whose value is assigned in the class.

What are the Methods of a Class in Python?

In Object-oriented programming using Python, we can define the following three types of methods within the class.

1. Instance method: Used to access or modify the object state. If we use instance variables inside a method, such methods are called instance methods.
2. Class method: Used to access or modify the class state. To implement a class method, a special code decorator @classmethod is used.
3. Static method: A method that performs a task in isolation without needing the object or class.

Read more: Difference Between Class Methods, Static Methods, and Instance Methods in Python

Example:

class Car:
    # class variable
    speed_measurement = "KM/hr"
  
      def __init__(self, model, brand, color):
          # data members (instance variables)
          self.model = model
          self.brand = brand
          self.color = color
  
      # Behavior (instance methods)
      def info(self):
          print('Model:', self.model, 'Brand:', self.brand, 'Color:', self.color)
  
    # class method
      @classmethod
      def set_speed_measurement(cls, new_measurement):
          # modify class variable
          cls.school_name = new_measurement
          return None
  
Highlighted code sample.

Naming Convention of a Class in Python

Naming conventions are essential in any programming language for better readability.

And writing readable code is one of the guiding principles of the Python language.

There are specific rules to follow when we are deciding on a name for a class in Python.

  • Rule 1: Class names should be CamelCase
  • Rule 2: Names of Exception classes should end in Error.
  • Rule 3: When creating a callable class, we can give a class name using the naming convention of a function.
  • Rule 4: Python's built-in classes are typically lowercase words

Use of pass Statement in a Python Class

In Python, the pass is a null statement used to have an empty block in a code or as a placeholder when we do not know what code to write or want to add the code in a future release.

Suppose we want to define a class that is not implemented yet, but we want to implement it in the future.

We cannot have an empty body because the interpreter gives an error.

So use the pass statement to construct a body that does nothing.

Example

class Demo:
    pass
  
Highlighted code sample.

In the above example, we defined class without a body. To avoid errors while executing it, we added the pass statement in the body of the class.

Use of self Parameter in Python Methods

In python, every instance method in a class must have a first parameter called “self” in the method definition.

The self parameter is mandatory whether there is an additional parameter for that instance method.

We do not give a value for this parameter when we call the method, Python provides it.

Use of the init method in Python Class

In Python, the init method is a constructor used to initialize the object's states and attributes.

Like methods, a constructor also contains a collection of statements that are executed at the time of an Object's creation.

It is the first method that runs as soon as an object of a class is instantiated.

Wrap Off

A class is a code template for creating another construct called an object.

A class in python has attributes and methods for modifying those attributes using instances called objects.

If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.

Please share this post and for more insightful posts on business, technology, engineering, history, and marketing, subscribe to our newsletter.

Next Tutorial — What is an Object? How to Create, Access, Modify and Delete an Object in PythonGet the Complete Code of Object Oriented Programming in Python on Github.

Connect with me.

Need an engineer on your team to grease an idea, build a great product, grow a business or just sip tea and share a laugh?