
Class in Python
Class is an important topic in Object-Oriented Programming (OOP).
A class is like a blueprint. It is used to create objects.
What is a Class?
A class is created using the class keyword.
class Student:
name = "Sathwik"
student1 = Student()
print(student1.name)
Output:
Sathwik
Here, student is the class and student1 is the object.
What is an Object?
An object is created from a class.
An object is an instance of class.
class Student:
name = "Sathwik"
student1 = Student()
print(student1.name)
Here:
- student → Class
- student1→ Object
- name → Attribute
We can create multiple objects from the same class.
Class with __init__()
The __init__() method is used to initialize object data.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student1 = Student("Sathwik", 21)
print(student1.name)
print(student1.age)
Output:
Sathwik
21
The self keyword refers to the current object.
Class with a Method
A function inside a class is called a method.
class Student:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello", self.name)
student1 = Student("Sathwik")
student1.greet()
Output:
Hello Sathwik
Multiple Objects
One class can be used to create many objects.
class Student:
def __init__(self, name):
self.name = name
student1 = Student("Sathwik")
student2 = Student("Rahul")
print(student1.name)
print(student2.name)
Output:
Sathwik
Rahul
Class Attribute
A variable created directly inside a class is called a class attribute.
class Student:
college = "ABC College"
student1 = Student()
print(student1.college)
Output:
ABC College
Instance Attribute
Variable unique to each individual object
A variable created using self is called an instance attribute.
class Student:
def __init__(self, name):
self.name = name
student1 = Student("Sathwik")
print(student1.name)
Here, name belongs to the particular object student1.
Join Techsnap Creators
Share your knowledge and earn ??
Want to showcase your tech expertise and get rewarded for your insights? Join the Techsnap creator network!
Write insightful blogs, stay ahead of industry trends, and grow your professional brand while helping others in the community.
Ready to make an impact?

Comments