Classes and Objects in Python - Interview Questions and Answers
A class is a blueprint for creating objects. It defines attributes (data) and methods (functions) that objects created from the class will have.
An object is an instance of a class. It contains data (attributes) and methods to perform operations.
class MyClass:
def __init__(self, name):
self.name = name
__init__ is a special method (constructor) used to initialize an object's attributes when an object is created.
A class is a blueprint, whereas an object is an instance created using the class.
The self keyword represents the instance of the class. It is used to access attributes and methods within the class.
obj = MyClass("example")
class MyClass:
def my_method(self):
print("This is a method.")
Yes, attributes can be defined at the class level
class MyClass:
class_attribute = "value"
Attributes defined inside the __init__ method, unique to each instance of the class.
Class attributes are shared across all instances, whereas instance attributes are specific to each object.
del obj.attribute_name
A static method does not depend on an instance of the class and is defined using the @staticmethod decorator.
@staticmethod
def static_method():
print("Static Method")
A class method operates on the class itself, not an instance, and is defined using the @classmethod decorator.
@classmethod
def class_method(cls):
print("Class Method")
@staticmethod: No access to class or instance data.@classmethod: Has access to the class (cls).
class Parent:
pass
class Child(Parent):
pass
Overriding occurs when a subclass provides a specific implementation for a method already defined in its superclass.
Polymorphism allows methods in different classes to have the same name but behave differently.
Using isinstance().
isinstance(obj, MyClass)
is checks for object identity, whereas == checks for value equality.
When a class inherits from more than one parent class.
class Child(Parent1, Parent2):
pass
Python uses the Method Resolution Order (MRO), determined by the C3 Linearization algorithm.
A metaclass is a class of a class that defines how a class behaves.
__new__ is used to create a new instance, while __init__ initializes the created instance.
super() is used to call a method from the parent class
Encapsulation restricts direct access to data by using private or protected attributes.
- Protected:
_attribute(accessible by subclass). - Private:
__attribute(name mangling applied).
Name mangling adds _ClassName as a prefix to private variables to avoid conflicts.
Use the abc module.
from abc import ABC, abstractmethod
class AbstractClass(ABC):
@abstractmethod
def abstract_method(self):
pass
Yes, using multiple inheritance.
Magic methods (or dunder methods) are special methods with double underscores, such as __init__, __str__, etc.
__str__: Returns a readable string representation of the object.__repr__: Returns an unambiguous representation for debugging.
__add__: Used for addition (+).__iadd__: Used for in-place addition (+=).
Implement the __call__ method.
class CallableClass:
def __call__(self):
print("Object called!")
It stores all the attributes of an object in a dictionary.
Use magic methods like __add__, __sub__, etc.
__eq__ defines equality, while __hash__ defines the hash value used in sets and dictionaries.
It limits the attributes that objects of a class can have, reducing memory usage.
Use the copy module.
import copy
clone = copy.deepcopy(obj)
- Shallow Copy: Copies the reference to the objects.
- Deep Copy: Copies the objects and their nested elements.
A class that allows only one instance. Can be implemented using a metaclass.
Decorators that modify the behavior of a class.
Python's dynamic typing where the object's behavior determines its type.
type() checks the exact type, while isinstance() checks inheritance.
Immutable objects like tuples can't be modified, but their mutable elements can.
It returns the memory address of an object.
Implement __eq__ and other comparison magic methods like __lt__.
Use del obj. Python's garbage collector will clean up the memory.
Define __iter__ and __next__ methods.
It is used to create getter methods for class attributes.
Tutorials
Random Blogs
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- Ideas for Content of Every niche on Reader’s Demand during COVID-19
- What to Do When Your MySQL Table Grows Too Wide
- Store Data Into CSV File Using Python Tkinter GUI Library
- SQL Joins Explained: A Complete Guide with Examples
- Create Virtual Host for Nginx on Ubuntu (For Yii2 Basic & Advanced Templates)
- Best Platform to Learn Digital Marketing in Free
- Variable Assignment in Python
- Top 15 Recommended SEO Tools
- Deep Learning (DL): The Core of Modern AI
