Q1. What is a class in Python?
A class is a blueprint for creating objects. It defines attributes (data) and methods (functions). Objects are instances of a class. Example:
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says woof")Q2. What is the __init__ method?
__init__ is a constructor method that is called when an object is instantiated. It initializes the instance attributes. The self parameter refers to the instance itself. Example:
obj = Dog("Buddy")Q3. What is the difference between instance variable and class variable?
Instance variables are defined within methods using self and are unique to each instance. Class variables are defined directly in the class body and are shared among all instances. Example:
class MyClass:
class_var = 0
def __init__(self, val):
self.instance_var = valQ4. What is self?
self is a reference to the current instance of the class. It is the first parameter of instance methods. When calling a method, Python automatically passes the instance as self. It can be named anything, but self is conventional.
Q5. How do you create an object from a class?
Instantiate the class by calling it like a function. Example:
my_dog = Dog("Rex")
my_dog.bark() This calls __init__ with the provided arguments.