Day - 32 of DevOps

Day - 32 of DevOps

Class And Objects in Python

Hello Everyone,

Welcome to Day 32 of DevOps Learning, Today we explore Python Class And Objects.

We all know that python is an Object Oriented Programming Language. An Object is created from the Class.

First, we will look into what is Class in Python.

What is Class?

In programming, a Class is a blueprint for the object. In a class, we define all properties (this includes attributes and methods) of the object. With that class, we can create any number of objects.

Syntax for Class:-

class ClassName:
    # Statement

Let's see an example,

class Bike:
    name = ""
    gear = 0

Here,

  1. Bike - the name of the class

  2. name/gear - variables inside the class with default values "" and 0 respectively.

Note: The variables inside a class are called attributes.

Python Objects

An object is called an instance of a class.

Suppose Bike is a class then we can create objects like bike1, bike2, etc from the class.

Here's the syntax to create an object.

objectName = ClassName()

Let's see an example,

# create class
class Bike:
    name = ""
    gear = 0

# create objects of class
bike1 = Bike()

Here, bike1 is the object of the class. Now, we can use this object to access the class attributes.

Access Class Attributes Using Objects

We use the . notation to access the attributes of a class. For example,

# modify the name property
bike1.name = "Mountain Bike"

# access the gear property
bike1.gear

Here, we have used bike1.name and bike1.gear to change and access the value of name and gear attributes, respectively.

Example 1: Python Class and Objects

# define a class
class Bike:
    name = ""
    gear = 0

# create object of class
bike1 = Bike()

# access attributes and assign new values
bike1.gear = 11
bike1.name = "Mountain Bike"

print(f"Name: {bike1.name}, Gears: {bike1.gear} ")

Output

Name: Mountain Bike, Gears: 11

In the above example, we have defined the class named Bike with two attributes: name and gear.

We have also created an object bike1 of the class Bike.

Finally, we have accessed and modified the properties of an object using the . notation.

Congrats🎉, On Learning the Python classes & objects

Happy Learning :)