bing
Flat 10% & upto 50% off + 10% Cashback + Free additional Courses. Hurry up
×
UPTO
50%
OFF!
Intellipaat
Intellipaat
  • Live Instructor-led Classes
  • Expert Education
  • 24*7 Support
  • Flexible Schedule

Classes and Objects in Python

Python is an object-oriented language and almost every entity in Python is an object. Which means that programmers extensively use classes and objects when coding in Python. Objects in Python are basically an encapsulation of variables and functions, that they get from classes. In this module you will learn each and every aspect of classes and objects in Python in the following order:

So without any further delay, let’s get started.
Watch this video on Python Classes and Objects.

What are Classes and objects in Python?

A class is simply a logical entity that behaves as a prototype or a template to create objects while the object is just a collection of variables and functions. Variables and functions are defined inside the class and are accessed using objects. These variables and functions are collectively known as attributes.

Let’s take an example to understand the concept of Python classes and objects. You can think of an object as a regular day to day object, say, a car. Now as discussed above, we know that a class has the data and functions defined inside of it, all this data and functions can be considered as features and actions of the object respectively. That means, that the features(data) of the car(object) are color, price, number of doors, etc. The actions(functions) of the car(object) are speed, applying brakes, etc. Multiple objects with different data and functions associated with them can be created using a class as depicted by the following diagram.

Python classes

Advantages of using Python classes

  • Classes provide an easy way of keeping the data members and methods together in one place which helps in keeping the program more organized.
  • Using classes also provides other functionality of object-oriented programming paradigm such as inheritance.
  • Classes also help in overriding any standard operator.
  • Using classes provides the ability to reuse the code which makes the program more efficient.
  • Grouping the related functions and keeping them in one place (inside a class) provides a clean structure to the code which increases the readability of the program.

Defining a class

Just as functions in python are defined using the keyword def, the classes in Python are defined using the keyword class, followed by the class name.

Much similar to functions we use docstrings in classes as well. Although the use of docstring is not mandatory but still recommended as it is considered as good practice to include a brief description about the class to increase the readability and understandability of the code.
Following example illustrate how to define a class.

class IntellipaatClass:
“‘Doctring statement here'”

he create class will create a local namespace for all the attributes including the special attributes tht start with double underscores (__), for example __init__() and __doc__(). As soon as the class is created, a class object is also created which is used to access the attributes in the class as shown in the following example:

class IntellipaatClass:
a = 5
def function1(self):
print(‘Welcome to Intellipaat’)
#accessing attributes using the class object of same name
IntellipaatClass.function(1)
print(IntellipaatClass.a)

Output:

Welcome to Intellipaat
5

Create an Object

We saw in the previous topic that the class object of the same name as the class is used to access the attributes. That is not all the class object is used for, it can also be used to create new objects and then those objects can be used to access the attributes as shown in the following example:

class IntellipaatClass:
a = 5
def function1(self):
print(‘Welcome to Intellipaat’)#creating a new object named object1 using class object
object1 = IntellipaatClass()
#accessing the attributes using new object
object1.function1()

Output:

Welcome to Intellipaat

You must have noticed that we are using a parameter named self while defining the function in the class but then we’re not really passing any value while calling the function. That is because when a function is called using an object, the object is itself passed automatically to the function as an argument, so object1.function1() is equivalent to object1.function1(object1). That’s why the very first argument in the function must be the object itself, which is conventionally called self. It can be named something else too but naming it “self” is a convention and it is considered as good practice to follow the convention.
Data science masters program

The_init_() function

The __init__ function is a reserved function in Python classes which is automatically called whenever a new object of the class is instantiated. As a regular function, init function is also defined using def keyword. As per the object-oriented programing paradigm, these types of functions are called constructors. We use constructors to initialize the variables. We can pass any number of arguments while creating the class object as per the definition of init function definition.

Following example illustrates how to use of __init__() function.

class IntellipaatClass:
def __init__(self, course):
self.course = course
def display(self):
print(self.course)object1 = IntellipaatClass(“Python”)
object1.display()

Output:

Python

In the above example, the init function behaves as a constructor and is called automatically as soon as “object1 = IntellipaatClass(“Python”)” this statement is executed. Since it is a function inside a class, the first argument passed in it is the object itself which is caught in the self parameter. The second parameter, that is course, is used to catch the second argument passed through the object, that is Python. And then we have initialized the variable course inside the init function. Further, we have defined another function named display to print the value of the variable. This function is called using object1.

Note: Don’t forget to give proper indentation in the above code.

Inheritance and its types

As a result of being an object-oriented programming language, Python also utilizes the inheritance. The ability of one class to inherit the properties of some other class is known as inheritance. The class that inherits the properties is called is usually called the sub-class or derived class. And the class that is being inherited is known as superclass or base class.

Inheritance provides code reusability of code as we can use an existing class and it’s properties rather than creating a class from scratch with the same properties.

class derived_Class_Name (base class):
<class-suite>

The derived class can inherit multiple classes at a time by mentioning all the base classes inside the bracket.

Example:

class Intellipaat:
def course(self):
print(“Python tutorial”)
class hello:
def func(self):
print(“Welcome to intellipaat)ob1 = hello()
ob1.func()
ob1.course()

Output:

Welcome to Intellipaat
Python tutorial

There are different forms of inheritance depending on the structure of inheritance taking place between a derived class and base class. Let’s discuss each one of them individually:

1. Single inheritance: The type of inheritance when a class inherits only one base class is known as single inheritance. Like we saw in the above example.

2. Multiple inheritance: When a class inherits multiple base classes then it’s known as multiple inheritance. Unlike some other languages like Java, Python fully supports multiple inheritance. All the base classes are mentioned inside the bracket as comma-separated list.
Example:

class BaseClass1():
def __init__(self):
print(“Blass class 1”)class BaseClass2():
def __init__(self):
print(“Base class 2”)class derivedClass (BaseClass1, BaseClass2):
def __init__(self):
BaseClass1.__init__(self)
BaseClass2.__init__(self)
print(“derived class”)
def display_all(Self):
print(self.ob1, self.ob2)ob = derivedClass()

Output:

Base class 1
Base Class 2
derived class

3. Multilevel inheritance: When the derived class inherits a base class and then another class inherits that previous derived class forming the parent, child and grandchild class structure then it’s known as multilevel inheritance.

class BaseClass():
def __init__(self):
print(“Base class”)class childClass(BaseClass):
def __init__(self):
print(“Child class”)class grandchildClass(childClass):
def __init__(self):
BaseClass.__init__(self)
childClass.__init__(self)
print(“Grand child class”)ob1 = grandchildClass()

Output:

Base class
Child class
Grand child class

4. Hierarchical inheritance: when there is only one base class inherited by multiple derived classes then its known as hierarchical inheritance

5. Hybrid inheritance: Hybrid inheritance is when there is a combination of the above mentioned inheritance types, meaning, a blend of more than one type of inheritance mentioned above.

Private attributes of a class

Sometimes while implementing inheritance, there are certain cases where we don’t always want that all the attributes of a class be inherited by the derived class. In those cases, we can make those attributes private members of the base class. We can simply do this by adding two underscores(__) before the variable name.

Example:

class Base1(object):
def __init__(self):
self.x = 10
# creating a provate variable named y
def __init__(self):
self.__y = 5class Derived1(Base1):
def __init__(self):
self.z = 20
Base1.__init__(self)ob1 = Derived1()
print(ob1.y)

When the above code block is executed, it will give the following error.
Output:

Traceback (most recent call last):
File “”, line 1, in
AttributeError: ‘Derived1’ object has no attribute ‘y’

Since, y is a private variable in Base class, the derived class is not able to access it.
With this, we come to an end of this module. the next module explains Python modules, see you there!

Previous Next

Download Interview Questions asked by top MNCs in 2019?

"0 Responses on Python Classes and Objects"

Leave a Message

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.
top

Sales Offer

Sign Up or Login to view the Free Python Classes and Objects.