Python Basics

Certification Training
3686 Learners
View Course Now!

Python Classes Tutorial

Welcome to lesson six, Classes tutorial, which is a part of the Python Course offered by Simplilearn. This lesson will provide detailed information on classes.

Objectives

After completing this lesson, you'll be able to:

  • Define a class and its advantages

  • Describe the method to create a class

  • Describe the method to add functions to a class

  • Describe the built-in class attributes

Python Classes

Python is an OOPS language so you can create classes and objects. Before creating classes and objects, you need to know the need of creating them in the first place.

Many built-in types of Python are being used every day. What if someone wants his own data types whose behavior and properties should be defined too.

For this, there should be a complete control over the defined behavior of this data type. You can do this by creating classes. Classes are nothing but user-defined data types. A class is just a blueprint defining the type of data that a user-defined data type can store and the kinds of operations that are supported by it.

The previous lessons elaborated on creating various variables of data types like variables of integer, string, float, and so on.

Here, we talk about creating variables of your own defined data types. These variables are called objects. Classes represent a simple way of depicting real-world things in the form of data types in programming.

Suppose you want to represent a car and store its properties and show what kind of things a car can perform. In such cases, you can create a car class which contains variables and functions.

Variables

For defining the properties of a car, you can create different variables inside the car class to store various properties like model number, build year, brand name, and so on.

Functions

The functions inside a class represent the kind of operations the real world things can do. So in the given example, a car can have functions like start, stop, apply brake, and so on.

Objects

As explained earlier, objects are the variables of a class data type. As you can create multiple variables of a data type (where each variable is capable of handling a different value), you can also create multiple objects of a class. Each object can store different values too.

In the given example, let's say you want to create an object car1 of type Car, then you can just write the given statement.

car1 = Car( )

You can also pass initial values to depict the properties of the car variable, as shown in the example.

car2 = Car(“Test model” , “Test Brand” )

Creating a Basic Class

To understand how a class can be created, let's see the example shown below.

Here you want to create a class named Vehicle. This class should be able to store the model name and the brand name for the class Vehicle.

You can create this class by using the keyword ‘class’, followed by the class name. After this, you can add various property names that you would want to include in this class.

class Vehicle:

model_name = “model x”

brand_name = “Brand y”

To create an object for this class, you can just write the given statement.

>>>car1 = Vehicle()

This will create an object named ‘car1’ of type vehicle.

Accessing Variables of a Class

After creating an object, you may need to access the value stored in different variables of that object. You can do this by using a dot operator. Append a dot after the name of an object for which you want to access a specific variable, and then give the name of that variable.  You will get the access to the desired value.

In the given example, If you want to access the model name of the variable car1, you can write the given print command. They will then print the model name for that particular object.

>>> print car1.model_name

output : model x

Similarly, you can print other variables of the same object as shown for printing a brand name in the given example.

>>> print car1.brand_name

output : brand y

Adding Functions to a Class

Till now, you have seen how variables are added to classes. To understand how to add functions to classes, you just need to define the function in the same way you had defined earlier.

But this time, it's definition should be written inside the class body. See the example below.

class Vehicle:

model_name = “model x”

brand_name = “Brand y”

def start(self):

print “Starting Vehicle...”

defstop(self):

print “Stop Vehicle...”

A start and a stop function have been created. If the start function is called, it should print “starting vehicle”. And if the stop function is called, it should print “stop vehicle”.

Note that the first argument to each method is self. Python adds the self-argument to the list. You do not need to include it when you call the methods.

Built-in Class Attributes

Built-in attributes can be accessed by using a dot operator like any other attribute. There are five types of built-in class attributes:

  • _dict_ attribute gives a dictionary containing the class’s namespace.

  • _doc_ attribute gives a class documentation string. It will return nothing if the documentation is not defined.

  • _name_ attribute gives a class name.

  • _module_ attribute gives the name of a module in which the class is defined. It's called _main_ in the interactive mode.

  • _bases_ attribute returns an empty tuple containing the base classes.

_Init_Function

Python classes have a special function called Init. It's called the class constructor, or initialization method that python calls when you create a new instance of such a class. It is called in a code when you create an object.

It allocates spaces for various objects. This function takes care of initializing objects. This means that it takes care of assigning values to variables of objects passed by the user.

As with other functions in a python class, the first argument to each method is self. Python then adds the self-argument to the list. You do not need to include it when you call the methods.

Example of Defining and Using a Class

To understand how to create a class in python, see the example given below:

class Student(object) :

name = “”

pass = True

def __int__(self, name):

self.name=name

def is_pass(self):

return self.pass

To create a student class, there are two variables in this class. The first variable is ‘name’, which is used to store the name of a student. The second variable is the ‘pass’ variable that contains the value True.

Seeing further, the constructor has also been defined. The first argument of the constructor is self, as explained in the previous sections.

The second argument is ‘name’. A name passed by the user has been assigned to the variable of this object. Similarly, one more function pass has been created above, which returns the value of the variable pass.

To explain the same example in more detail, it's important to know how to use a class.

Consider the example shown below.

## Defining object

student1 = Student(“David”)

##Using the object

print student1.is_pass()

Output : True

Create the object of the class student and assign the name ‘David’ to the name variable. On calling the init method and passing David to it, you can access the name variable of this object, or call it. This is called with the pass function using a dot operator. It will return a relevant value.

Summary

Let's summarize the topics covered in this lesson.

  • A class is a user-defined data type that’s used as a blueprint to create multiple objects. It is made of variables and functions.

  • Objects are variables of classes. You can create multiple objects of a class and each object can have different values for its variables.

  • The dot operator is used to access the values stored in different variables of that object.

  • Every Python class follows built-in attributes and they can be accessed using the dot operator like any other attribute.

  • Python classes have a special function called __init__, which is a class constructor.

Conclusion

With this, we have come to an end of this lesson on Python Classes.

  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Request more information

For individuals
For business
Name*
Email*
Phone Number*
Your Message (Optional)
We are looking into your query.
Our consultants will get in touch with you soon.

A Simplilearn representative will get back to you in one business day.

First Name*
Last Name*
Email*
Phone Number*
Company*
Job Title*