Classes and Objects in Python — Python Technical Interview Questions & Answers
Classes and Objects in Python
Classes and Objects in Python
- A class is the blueprint. An object is one real thing made from it. class Student: is the idea of a student. s = Student("Asha", 12) is one student sitting in the room. Two objects can have different names and rolls.
- __init__ runs when you create the object. self is that object. self.name = name stores the field on it. Forget self and you get TypeError or a variable that vanishes. Every method’s first parameter is self — you don’t pass it at the call site.
- Let’s take this on the board. class Student with __init__(self, name, roll). s = Student("Asha", 12). print(s.roll, s.name) → 12 Asha. Class is Student. Object is s. That is the whole idea for a fresher viva.
- Classes and Objects in Python — output: 12 Asha. Student is the class; s is one real object.
class Student (blueprint)
│ Student("Asha", 12)
▼
s1 Asha roll 12Technical Interview Tip: Explain self and __init__ together.
Code Examples for Classes and Objects in Python
Example
# Classes and objects
class Student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
s = Student("Asha", 12)
print(s.roll, s.name)
Classes and Objects in Python — output: 12 Asha. Student is the class; s is one real object.
How to Explain Classes and Objects in Python to an Interviewer
Explain Classes and Objects as if you are teaching a junior — definition, then one tiny script.
Class = blueprint Object = instance
What does the example print, and why?
Classes and Objects in Python — output: 12 Asha
What mistake do freshers make with Classes and Objects?
Self current object