Python Classes and Objects

  • Python

We know Python is an object-oriented programming language and we have been working with functions and now why do we need objects and classes? So, everything in python is all about objects.

Objects and Classes are an integral part of most of the object-oriented programming languages.

Classes can be considered as templates or blueprints which can be used to create multiple objects. Let’s consider Samsung as a Class and different phones to be multiple objects being created out of it which means an object is an instance of a class.

Defining a class

To define a function, we use def keyword. Similarly, to define a class we use class keyword followed by the name of the class and a colon :. The first letter of the class name is always Uppercase.

class Example:
  pass

A class can never be empty and you’ll have to give define some variables or methods(functions) or just pass.

class Car:
  type = "sedan"

  def start(self):
    print("Let's start the Engine")

print(Car.type)

print(Car.start)

Output :

sedan
<function Car.start at 0x7f281526d820>

In the above example, when we printed output for Car.start, it printed the location of the function because we did not call the function. So, how do we call the function? To understand this, we first need to know what objects are.

Defining an object

Creating an object in python is similar to calling a function. When we do this, we instantiate the class and create a new instance.

class Example:
  pass

obj = Example()

Here, obj is an object of the class Example.

Now, let’s understand the previous example. To call the function, we’ll first need to create an object of the class and then call the function.

class Car:
  type = "sedan"

  def start(self):
    print("Let's start the Engine")

print(Car.type)

car1 = Car()

car1.start()

Output :

sedan
Let's start the Engine

We have been using classes and objects from the very beginning but we just didn’t knew. The above example was a custom class that was defined by a user and python has built-in classes as well.

x = "Hello"
y = 9

print(type(x))
print(type(y))

Output :

<class 'str'>
<class 'int'>

You see, str and int are also classes. Similarly we have many built-in classes in python.