
Python Classes And Objects
Classes and Objects - Part 1: The Basics
What is a class?
A class is a blueprint where we can create objects in it and we can use it later.
for example:
class Student:
passIn the above example, Student is the class name.
What is an object?
An object is an instance of a class. Where we can write methods and data.
for example:
class Student:
pass
s1 = Student()Here, s1 is an object of the class Student.
Why do we need to use class?
The main use of class is we store data and methods in it. In programming, whenever we need to use that type of methods or data, we can simply call the class name and use that method.
What is __init __?
__init __ is a special method. It intializes automatically when we create an object.
for example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
s1 = Student("Rohith", 20)
print(s1.name) # Rohith
print(s1.age) # 20Here, when we created s1, __init__ ran automatically and stored "Rohith" and 20 into the object.
What is Self?
Self means "this object". It is used inside the class to refer to the current object we are working with.
for example:
class Student:
def __init__(self, name):
self.name = name
def show(self):
print(self.name)
s1 = Student("Kiran")
s2 = Student("Ravi")
s1.show() # Rohith
s2.show() # KrishnEven though both s1 and s2 came from the same class, self makes sure show() prints the correct name for each object.
Can we create many objects from one class?
Yes. One class can be used to create as many objects as we want, and each object keeps its own data separately.
for example:
class Student:
def __init__(self, name):
self.name = name
s1 = Student("Rohith")
s2 = Student("Ravi")
s3 = Student("Dev")
print(s1.name) # Rohith
print(s2.name) # Krishn
print(s3.name) # DevJoin 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