Classes and Objects

Class are blueprints to create objects which represent a collection of related properties and methods

Python is an object-oriented programming language.

Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes.

Creating a Class in Python

To define a class we can use class keyword and define the properties and methods inside it.

class Vehicle:
    number_of_wheels = 2
    color = "red"

In the above code snippet, we have declared a class called Vehicle with two properties color and number_of_wheelswith some default values.

Now that we have our class defined, let's create a object of the class Vehicle.

Creating an Object

To create a new object, simply reference the class you want to build the object out of. In this case, we'll use our previously defined Person class.

class Vehicle:
    number_of_wheels = 2
    color= "red"

vehicle1 = Vehicle() # Creating object of class Vehicle
print(vehicle1)
print("Vehicle1:", vehicle1.color)

Output:

<__main__.Vehicle object at 0x10ae31ae0>
Vehicle1: red

Awesome, we created an object of class Vehicle and accessed the color property.

Let us now make our classes useful.

Python Class Constructor

Constructors are special kind of method, used for instantiating an object.

  • The task of constructors is to initialize and assign values to the data members of the class when an object of the class is created.
  • In Python, the __init__()method is called the constructor and is always called when an object is created.
  • Python doesn?t support defining multiple constructors in a class. i.e constructor overloading is not supported by the language.
  • You can pass any number of parameters to the init method similar to how you can pass in parameters to functions. However, the first parameter should always be self.

Let us now define a constructor for Vehicle class:

class Vehicle:

    def __init__(self, color, number_of_wheels):
        self.color = color
        self.number_of_wheels = number_of_wheels

vehicle1 = Vehicle("Red", 4)
print(vehicle1)
print("Vehicle1:", vehicle1.color)

vehicle2 = Vehicle("Blue", 2)
print(vehicle2)
print("Vehicle2", vehicle2.color)

Output:

<__main__.Vehicle object at 0x114b0f3a0>
Vehicle1: Red
<__main__.Vehicle object at 0x114b0e470>
Vehicle2 Blue

Python Class Methods

Strings and numbers aren't the only thing you can define in classes. Objects can also contain functions. Let's create one in our Person class.

class Vehicle:

    def __init__(self, color, number_of_wheels):
        self.color = color
        self.number_of_wheels = number_of_wheels

    def drive(self):
        print("Drive mode on!")

    def stop(self):
        print("Drive mode off!")

vehicle1 = Vehicle("Red", 4)
vehicle1.drive()
vehicle1.stop()

Output:

Drive mode on!
Drive mode off!

References: