Classes in Python with Examples

We offer you a brighter future with FREE online courses - Start Now!!

In Python, we use classes to create objects. A class is a tool, like a blueprint or a template, for creating objects. It allows us to bundle data and functionality together. Since everything is an object, to create anything, in Python, we need classes. Let us look at the real-life example to understand this more clearly.

Real-Life Example on Classes

When a company wants to create a car, it can’t start building right away. First, it needs to create a blueprint of the car. In Python, the class is like the blueprint of the object, car. The blueprint allows the company to create as many cars as it wants. Similarly, we can create as many objects as we want from a class.

Creating Class in Python

We can define a class by using the keyword class.

The basic syntax of class is:

Syntax

class ClassName:
    #Statements..

Using the above syntax, let us create a class named Vehicle

Example of Classes in Python

class Vehicle:
    pass
print(Vehicle)

Output

<class ‘__main__.Vehicle’>

In the above code example, we’ve created an empty class with the name Vehicle.

Except for keywords, we can name the class anything. We can also use underscores but generally, PascalCase is recommended while naming classes.

Pass Statement in Python

Empty classes raise an error. To create an empty class without raising an error, we use the pass statement.

Example of Python Pass Statement

class Dog:
    pass
print(Dog)

Output

<class ‘__main__.Dog’>

We can see in the above code example, although the class is empty, Python didn’t raise an error.

Creating Object in Python

To create an object from the class, we use the following syntax:

Syntax

object_name = ClassName(*args)

Using the above syntax, we can create an object of class Vehicle.

Example of Object in Python

car = Vehicle()
print(car)

Output

<__main__.Vehicle object at 0x103f7d8b0>

In the above code example, we’ve created an object car from the class Vehicle.

This is also called object Instantiation.

In Python, objects consist of state, behavior, and identity.
1. Identity is the name of the object.

Example: car

2. In Python, every object has its unique state. We give each object its unique state by creating attributes in the __init__method of the class.

Example: Number of doors and seats in a car.

3. Behaviour of an object is what the object does with its attributes. We implement behavior by creating methods in the class.

Example: Accelerating and breaking in a car.

We will learn about attributes and methods in the coming sections.

Dot Operator in Python

In python, the dot operator is used to access variables and functions which are inside the class.

1. To access attributes

Syntax

object_name.attribute_name

2. To access methods

Syntax

object_name.method_name(*args)

Now, let’s see the syntax in action.

Example of Python Dot Operator

class Vehicle:
    wheels = 4

car = Vehicle()
print(car.wheels)

Output

4

In the above code example, we created an object car. We have declared a variable wheels inside the class Vehicle and accessed that variable using the dot operator.

3. To modify attributes

Syntax

object_name.attribute_name = value

Example

car.wheels = 10
print(car.wheels)

Output

10

In the above code example, we changed the value of wheels from 4 to 10 by using the dot operator.

The variable wheels is called a class attribute. We will learn more about it in the next section.

Attributes in Python

Variables that are declared inside a class are called Attributes. Attributes are two types: Class Attributes and Instance Attributes.

1. Class Attributes in Python

Class attributes are variables that are declared inside the class and outside methods. These attributes belong to the class itself and are shared by all objects of the class.

Example of Python Class Attributes

class Vehicle:
    wheels = 4

car = Vehicle()
van = Vehicle()

print(car.wheels)
print(van.wheels)

Output

4
4

In the above code example, the attribute wheels is a class attribute.

Since it is a class attribute, its value is shared by all objects of the class and in the above code example, the attribute wheels is shared by the two objects, car and van.

Class attributes can also be accessed by class name rather than an object name as shown in the below code example.

For Example:

print(Vehicle.wheels)

Output

4

Changing the value of a class attribute using the class name causes the value change in all objects of the class.

For Example

Vehicle.wheels = 10
print(Vehicle.wheels)
print(car.wheels)
print(van.wheels)

Output

10
10
10

Before going to instance attributes, we must first know about the __init__() method and self parameter

__init__() method in Python

It is similar to a constructor in Java and C++. It gets executed as soon as we create an object.

The values for the parameters in the __init__() method should be given while creating the object.

Example of Python __Ini__()

class Vehicle:
    wheels = 4

    def __init__(self, doors):
        print(f"Object created with doors = {doors}")

car = Vehicle(2)

Output

Object created with doors = 2

In the above code example, we created an __init__() method with parameters self and doors. Ignore the self parameter, for now, we will learn about it in the next section.

We can see that the __init__() method is called as soon as we instantiate an object.

__init__() method helps to provide the state of the object. Using it, we can assign different values to different objects.

The values of attributes in the __init__() method are unique to each object.

For Example

car = Vehicle(2)
van = Vehicle(6)

Output

Object created with doors = 2
Object created with doors = 6

In the above code example, the car and van both have a different value for the attribute doors.

Self parameter in Python

Almost all methods in the class have an extra parameter called self. It references the current object of the class.

Unlike other parameters, the value of the self is provided automatically by Python. Instead of self, we can name it anything we want as long as it is the first parameter of the method.

Example of Self Parameter in Python

class Vehicle:

    def __init__(self, name):
        self.name = name

vehicle1 = Vehicle("car")
vehicle2 = Vehicle("van")

print(vehicle1.name)
print(vehicle2.name)

Output

car
van

In the above code example, we used the self parameter to reference the current object.

Instance Attributes in Python

Instance attributes provide a state to an object. They are declared inside the __init__() method. Instance attributes are unique to each object and are not shared by other objects.

We can declare instance attributes in the __init__() method by using the dot operator and the self parameter.

Example of Python Instance Attributes

class Vehicle:
    wheels = 4

    def __init__(self, name, doors, seats):
        self.name = name
        self.doors = doors
        self.seats = seats

car = Vehicle("Car", 2, 2)
van = Vehicle("van", 6, 12)

print(car.name, car.doors, car.seats)
print(van.name, van.doors, van.seats)

Output

Car 2 2
van 6 12

In the above code example, each object’s attributes have unique values.

These attributes can only be accessed by the object name.

Class Attributes vs Instance Attributes

Class Attributes Instance Attributes
Shared by all objects of the class. Not shared by all objects of the class.
Same value for all objects. A Unique value for each object.
Declared outside the __init__() method. Declared inside the __init__() method.
Dot operator and self parameter are not needed. Dot operator and self parameter are needed to declare instance attributes.
Can be accessed with the class name and object name. Can only be accessed with object name.

Changing Class Attributes to Instance Attributes

When we try to change a class attribute using an object name, instead of changing the class attribute, Python creates an instance attribute with the same name as the class attribute and assigns the new value to the instance attribute.

This can be seen in the below code.

For Example

class Vehicle:
    wheels = 4

car = Vehicle()
van = Vehicle()

print("Old Values")
print(car.wheels)
print(van.wheels)

car.wheels = 2

print("New Values")
print(car.wheels)
print(van.wheels)

print("Instance attributes of car", car.__dict__)
print("Instance attributes of van", van.__dict__)

Output

Old Values
4
4
New Values
2
4
Instance attributes of car {‘wheels’: 2}
Instance attributes of van {}

In the above code, after trying to change the class attribute through the object car, Python created a new instance attribute in the object car.

Restricting Access in Python

We can prevent an object from accessing an attribute by prefixing double underscores to the attribute name. When an object tries to access such an attribute, it raises an AttributeError. This applies to both class attributes and instance attributes.

Class Attribute in python

For Example

class Vehicle:
    __name = "Car"
 
print(Vehicle.__name)

Output

AttributeError: type object ‘Vehicle’ has no attribute ‘__name’

Instance Attribute in Python

Example

class Vehicle:

    def __init__(self):
        self.__make = "Audi"

car = Vehicle()
print(car.__make)

Output

AttributeError: ‘Vehicle’ object has no attribute ‘__make’

Methods in Python

Functions inside a class are called Methods. They provide behavior to the class. Most of the methods have an extra parameter called self. We can access them in the same way we access attributes.

Example of Methods in Python

class Vehicle:
    wheels = 4

    def __init__(self, name, doors, seats):
        self.name = name
        self.doors = doors
        self.seats = seats

    def accelerate(self, distance):
        return f"{self.name} has travelled {distance} Miles."

car = Vehicle("Car", 2, 2)

print(car.accelerate(10))

Output

Car has travelled 10 Miles.

Class Inheritance in Python

When we need to create a class that is similar to the class we have defined earlier, we can simply inherit the old class. The class which got inherited is called a parent class or superclass and the class inheriting the parent class is called a child class or subclass. Child class contains all the methods of its parent class.

The basic syntax to inherit a class is

Syntax

class SubClass(SuperClass):

Example of Class Inheritance in Python

class ParentClass: # Superclass

    def parent_method(self):
        return "Method in parent class"

class ChildClass(ParentClass): # Subclass
    pass

child = ChildClass()

print(child.parent_method())

Output

Method in parent class

In the above code example, we create a parent class with the method which returns a string. Then we created a child class that inherited the parent class.

Although it looks like the child class is empty, it is not. Child class can access all the methods of its parent class.

When we called the parent_method() using the object child, it invoked the method in its parent class.

We also have the ability to override the methods of a parent class.

For Example

class ParentClass: # Superclass

    def parent_method(self):
        return "Method in parent class"

class ChildClass(ParentClass): # Subclass

    def parent_method(self):
        return "Method in child class"

child = ChildClass()

print(child.parent_method())

Output

Method in child class

In the above code example, the new method in the child class overrides the old method in the parent class. This overriding of methods also comes under the Polymorphism concept.

Class Inheritance provides reusability of code and saves a ton of time when we need to create multiple classes.

issubclass() in python

issubclass () is a Python built-in function. It is used to find whether a class is a subclass or not. It returns True if the passed class is a subclass to another passed class, otherwise False.

For Example

print(issubclass(ChildClass, ParentClass))

Output

True

Polymorphism in Python Class

Polymorphism is the ability to occur in different forms depending on the condition. It simply means using the same block of code to accomplish different objectives. In Python, we can use this concept while creating multiple classes.

We can create multiple classes with the same method names and we can call those methods of different classes using a single variable with the help of Polymorphism.

Example of Polymorphism in Python

class Solomon:

    def __init__(self):
        self.name = "Solomon"
        self.age = 50

    def get_name(self):
        print(f"Hello, my name is {self.name}.")

    def get_age(self):
        print(f"I am {self.age} years old.")

person1 = Charles()
person2 = Solomon()

for person in (person1, person2):
    person.get_name()
    person.get_age()

Output

Hey! I am Charles.
I am 20 years old.
Hello, my name is Solomon.
I am 50 years old.

In the above code example, although both classes have no relationship, we still used the same variable person to call methods of different classes. This is known as Polymorphism.

Abstract Class in Python

We know classes work like a blueprint to objects. When we are creating multiple complex classes, we need to have a blueprint class to create other complex classes. This blueprint class is called an abstract class.

Abstract class is a template for other classes. Like the name suggests, it is only abstract and can not be instantiated. A class should contain at least one abstract method to become an abstract class. We can create abstract classes by using the abc module.

From the abc module, we need to import ABC class to inherit and abstractmethod decorator to create abstract methods. Abstract classes can have a normal method and an abstract method.

Example of Abstract Class in Python

from abc import ABC, abstractmethod

# abstract class
class Employee(ABC):

    @abstractmethod
    def sector(self):
        pass

class GovtEmployee(Employee):

    # Overriding abstract method
    def sector(self):
        print("I work in Government sector")

class PrivateEmployee(Employee):

    # Overriding abstract method
    def sector(self):
        print("I work in Private sector")

emp1 = GovtEmployee()
emp2 = PrivateEmployee()

emp1.sector()
emp2.sector()

Output

I work in Government sector
I work in Private sector

In the above code example, we created an abstract class Employee. Using the abstract class, we created two more classes.

For Example

emp = Employee()

Output

TypeError: Can’t instantiate abstract class Employee with abstract methods sector

In the above code example, Python raised a TypeError when we tried to instantiate an abstract class.

Built-in Functions for Attributes in Python

In Python, we have a few built-in functions to access/modify class attributes. They are explained below:

1. getattr() in python

It is used to access the attribute of an object. It returns the value of the given attribute.

Example of getattr() in Python

class Vehicle:
    color = "Blue"

car = Vehicle()
print(getattr(car, 'color'))

Output

Blue

2. hasattr() in python

It is used to verify whether a given attribute exists or not. It returns True if it exists, otherwise False.

print(hasattr(car, 'color'))

Output

True

3. setattr() in Python

It is used to set an attribute. If the given attribute does not exist, then it would be created.

For Example

# Changing an existing attribute
print("Color before", car.color)
setattr(car, 'color', 'Red')
print("Color after changing", car.color)

# Creating a new attribute
setattr(car, 'speed', 120)
print(car.speed)

Output

Color before Blue
Color after changing Red
120

4. delattr() in Python

It is used to delete an attribute. It raises an AttributeError if we try to access it after deleting or if we pass object name instead of class name as its first argument.

For Example

delattr(Vehicle, 'color')
print(Vehicle.color)

Output

AttributeError: type object ‘Vehicle’ has no attribute ‘color’

del Keyword in Python

In Python, the del keyword can be used to delete classes, objects and its attributes. If we try to access a deleted class or object, it raises a NameError and if we try to access a deleted attribute, it raises an AttributeError.

Syntax

del object_name

To Delete a Class in Python

class PythonGeeks:
    domain = ".com"

print("Before Deleting", PythonGeeks)

del PythonGeeks

try:
    print(PythonGeeks)
except NameError:
    print("Class Deleted")

Output

Before Deleting <class ‘__main__.PythonGeeks’>
Class Deleted

In the above code example, we deleted the Class PythonGeeks and it raised a NameError when we tried to access it again.

To delete an Attribute in python

Example of how to delete attribute in python

class PythonGeeks:
    domain = ".com"

print("Before DeletingA Attribute = ", PythonGeeks.domain)

del PythonGeeks.domain

try:
    print(PythonGeeks.domain)
except AttributeError:
    print("Attribute Deleted")

Output

Before DeletingA Attribute = .com
Attribute Deleted

In the above code example, we deleted the attribute domain and it raised an AttributeError when we tried to access it again.

Built-in Attributes in Python

Python gives us a few built-in attributes to get more information about a class when necessary. There are various Built-in Attributes in Python. Let’s see them:

1. __dict__

This attribute contains the dictionary containing the class’s namespace.

For Example

class Vehicle:
    pass

print(Vehicle.__dict__)

Output

{‘__module__’: ‘__main__’, ‘__doc__’: ‘ A template for all vehicles ‘, ‘__dict__’: <attribute ‘__dict__’ of ‘Vehicle’ objects>, ‘__weakref__’: <attribute ‘__weakref__’ of ‘Vehicle’ objects>}

2. __name__

This attribute contains the class name.

For Example

print(Vehicle.__name__)

Output

Vehicle

3. __module__

This attribute contains the name of the module in which the class is defined.

The attribute is “__main__” in interactive mode.

For Example

print(Vehicle.__module__)

Output

__main__

4. __bases__

This attribute contains the tuple containing the class’s base classes.

For Example

print(Vehicle.__bases__)

Output

(<class ‘object’>,)

5. __doc__

This contains a string of the documentation of the class. It is None if no documentation is defined.

For Example

print(Vehicle.__doc__)

Output

None

We can declare a docstring using ”’triple single quotes” or “””triple double quotes””” just after the class declaration.

For Example

class Vehicle:
    """To demonstrate docstring"""

print(Vehicle.__doc__)

Output

To demonstrate docstring

Interview Questions on Python Classes

Q1. Create an empty class and an object for the class without raising an error.

Ans 1. Code is as follows:

class DoesNothing:
    pass

obj = DoesNothing()

Q2. Create a class named Square and initialize it with length. Create two methods to return perimeter and area.

Ans 2. Code is as follows:

class Square:

    def __init__(self, length):
        self.length = length

    def getPerimeter(self):
        return round(4 * self.length)

    def getArea(self):
        return round(self.length * self.length)

Q3. Create a class named Employee and initialize with name and id. Create a common attribute for all objects named retirement_age with a value of 50. Also create methods:

years_to_work() – Returns how many years an employee has to work until retirement from his current age.
setSalary() – Assign salary to the employee
getSalary() – Returns salary of the employee

Ans 3. Complete code is as follows:

class Employee:
    retirement_age = 50

    def __init__(self, name, id):
        self.name = name
        self.id = id
        self.salary = None
        self.remaining_years = None

    def years_to_work(self, present_age):
        self.remaining_years = self.retirement_age-present_age
        return self.remaining_years

    def setSalary(self, salary):
        self.salary = salary

    def getSalary(self):
        return self.salary

Q4. What is the output of the following code?

class Person:

    """Basic template of Person"""

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def eat(self):
        return f"{self.name} is Eating"

    def birthday(self):
        self.age += 1
        return f"{self.name} is now {self.age} years old."

jack = Person("Jack", 2)

print(jack.__doc__)
print(jack.eat())
print(jack.birthday())

Ans 4. The output is

Basic template of Person
Jack is Eating
Jack is now 3 years old.

Q5. A few weeks ago, Sam created a class named Fruit and sent the file to his friend. His friend came across a bug and informed Sam about it. After spending hours thinking, he is now sure that the bug is being caused by a certain attribute in the class. He is not sure whether it is being caused because of its presence or absence. Since he can not directly edit the file, he decided to send his friend another file that modifies the already existing class. He wants to delete the attribute lemons if it exists or if it doesn’t exist, then he wants to create it with value 24. Help Sam finish the code.

Ans 5. Complete code is as follows:

if hasattr(Fruit, 'lemons'):
    delattr(Fruit, 'lemons')

else:
    setattr(Fruit, 'lemons', 24)

Quiz on Classes in Python

Conclusion

In this article, we learned about the classes. Specifically when to use classes, how to use classes, objects, attributes, and methods. We have also gone through different types of attributes, __init__() method, various built-in functions, and built-in attributes.

Furthermore, if you have any queries or thoughts, please do not hesitate to share them with us in the comment section.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


2 Responses

  1. Daniel Sorak says:

    Review Question 4 answer is incorrect:

    4. Question
    Statement 1: Instance attributes can be accessed by class name.
    Statement 2: Instance attributes are unique to each object.

    Only Statement 2 is true, but when I chose that, it marked it as incorrect and indicated that the correct answer is “Both statements are true”, which is not the case.

    Also note that Question 6 is _identical_, but indicated the correct answer: “Statement 2 is true”

  2. Haseen Ullah Khan says:

    very helpfull

Leave a Reply

Your email address will not be published. Required fields are marked *