Class in Python
In Python, a class is a blueprint for creating objects. It defines attributes (variables) and methods (functions) that the objects created from the class can use. Classes help us follow Object-Oriented Programming (OOP) principles like encapsulation, inheritance, and polymorphism.
In Python, a class is created using the class keyword.
Syntax
class ClassName:
# Constructor (special method to initialize object)
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1 # Instance variable
self.attribute2 = attribute2
# Method
def display(self):
print(f"Attribute1: {self.attribute1}, Attribute2: {self.attribute2}") Example: Creating and Using a Class.
Syntax
# Create class with name Student
class Student:
# Constructor
def __init__(self, name, age): # initialization happens here
self.name = name # instance variable
self.age = age
# Class variable
company = "Google"
# Method
def introduce(self):
print(f"My name is {self.name} and I am {self.age} years old.")
# Create objects (instances of the class)
s1 = Student("Ashish", 29) # initialization happens automatically
s2 = Student("Katrina", 25)
# Call methods
s1.introduce()
s2.introduce()
# Access instance variables
print(s1.name)
print(s2.age)
print(s1.company)
print(s2.company) The output of the above code is:
My name is Ashish and I am 29 years old.
My name is Katrina and I am 25 years old.
Ashish
25
Google
Google
Object Creation with Python Class We can create the objects of the class. The class object could be used to access different attributes of the class. Attributes may be data or methods.
Object creation is the allocation of memory for a new object of a class. In Python, object creation happens when we call the class name like a function:
Python
s1 = Student("Ashish", 29) # Object creation happens here At this moment, Python creates an empty object in memory (not yet filled with values).
Python
# Empty list my_list = [] # List with elements fruits = ['apple', 'banana', 'cherry'] # Mixed data types mixed_list = [1, 'hello', 3.14, True]