Classes and Objects in Python

Python : Classes and Objects

A class is a blueprint or a template for creating objects, which are instances of the class. An object is simply a collection of data (variables) and methods (functions) that act on those data.

How to Define Class in Python

To define a class, we use the class keyword followed by the name of the class. We can also define an optional constructor method using the __init__() function, which gets called when an object of the class is created.

class Person:
    def __init__(self, name, age): = name
        self.age = age

    def greeting(self):
        print(f"Hello, my name is {} and I am {self.age} years old.")

How to Create object in Python

To create an object of the Person class, we simply call the class like a function and pass in the required arguments:

person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

print(, person1.age)  # output: Alice 25
print(, person2.age)  # output: Bob 30

Class-level attribute and method

In addition to attributes and methods, classes can also have class-level attributes and methods. Class-level attributes are shared among all instances of the class, while class-level methods act on the class itself rather than an instance of the class.

class Circle:
    pi = 3.14159  # class-level attribute

    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return self.radius ** 2 * Circle.pi  # class-level attribute accessed through the class name

    def set_pi(cls, value):
        cls.pi = value  # class-level attribute updated through the class method

In above example, we define a class called Circle with a class-level attribute called pi and a method called area that calculates the area of the circle. We also define a class-level method called set_pi that allows us to update the value of the pi attribute.

To create an object of the Circle class, we simply call the class like a function and pass in the required arguments:

circle1 = Circle(5)
circle2 = Circle(10)

// call the area method on each object to calculate the area of the circle:
print(circle1.area())  # output: 78.53975
print(circle2.area())  # output: 314.159

// update the value of the pi attribute using the set_pi method:
print(circle1.area())  # output: 78.5
print(circle2.area())  # output: 314.0