Q1). What is Object-Oriented Programming (OOP) in Python?
OOP is a programming style that uses objects and classes to organize code. Objects are instances of classes, which act as blueprints for creating these objects.
For example: consider a `Car` class. A `Car` object might be a specific car like a 'Toyota Corolla', with attributes like color and model, and methods like `drive()` and `brake()`. This approach helps in structuring code in a way that models real-world entities.
Q2). What is a class in Python?
A class is like a blueprint for creating objects. It defines a set of attributes (properties) and methods (functions) that its objects will have. For instance, a `Book` class might define attributes like `title`, `author`, and `year`, and methods like `read()` and `get_summary()`. Each `Book` object created from this class will have these attributes and methods.
Q3). What is an object in Python?
An object is an instance of a class. It represents a specific example of a class with its own data.
For example: if `Car` is a class, then `my_car = Car('red', 'Toyota')` creates an object `my_car` with the color 'red' and make 'Toyota'. Each object can have different attribute values.
Q4). What is an attribute in Python OOP?
An attribute is a variable that belongs to an object or class.
For example: in a `Person` class, attributes might include `name` and `age`. If you create a `Person` object named `john`, you might set `john.name = 'John'` and `john.age = 30`. These attributes store data about each person object.
Q5). What is a method in Python OOP?
A method is a function defined inside a class that operates on objects of that class.
For example: a `Dog` class might have a method `bark()` that prints 'Woof!'. When you call `my_dog.bark()`, it executes the `bark` method for the `my_dog` object.
Q6). What is inheritance in Python?
Inheritance allows one class (child class) to inherit attributes and methods from another class (parent class).
For example: if `Animal` is a parent class with attributes `name` and `age`, a child class `Dog` can inherit these attributes and add its own attributes like `breed`. This promotes code reuse.
Q7). What is encapsulation in Python?
Encapsulation is the practice of bundling data (attributes) and methods that operate on the data into a single unit (class) and restricting direct access to some of the object's components.
For example: a `BankAccount` class might have private attributes like `balance` and methods like `deposit()` and `withdraw()` to safely modify `balance`.
Q8). What is polymorphism in Python?
Polymorphism allows different classes to be treated as instances of the same class through a common interface.
For example: if both `Cat` and `Dog` classes have a method `make_sound()`, you can call `make_sound()` on any animal object, and it will produce the sound specific to that animal.
Q9). What is the `self` keyword in Python?
The `self` keyword represents the instance of the class. It allows access to attributes and methods of the class within its methods.
For example: in the method `def set_color(self, color):`, `self.color = color` sets the `color` attribute of the current object.
Q10). What is a constructor in Python?
A constructor is a special method `__init__` used to initialize a new object's attributes.
For example: in `class Car: def __init__(self, color, make): self.color = color self.make = make`, `__init__` sets the `color` and `make` attributes when a new `Car` object is created.
Q11). How do you create an object in Python?
To create an object, you call a class like a function.
For example: `my_car = Car('red', 'Toyota')` creates an object `my_car` of class `Car` with color 'red' and make 'Toyota'.
Q12). What is method overriding in Python?
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
For example: if `Animal` has a method `make_sound()`, `Dog` can override this method to bark by defining its own `make_sound()`.
Q13). What is method overloading in Python?
Python does not support method overloading in the traditional sense, but you can achieve similar behavior using default arguments or variable-length arguments.
For example: a method `def greet(self, name=None):` can handle both cases with and without a name.
Q14). What is the `super()` function used for?
The `super()` function allows you to call methods from a parent class from within a child class.
For example: `super().__init__()` in a child class constructor calls the parent class's constructor to initialize inherited attributes.
Q15). What are class methods in Python?
Class methods are methods bound to the class rather than its instances. They use `cls` as their first parameter instead of `self`.
For example: `@classmethod def create_dog(cls, name): return cls(name)` allows creating a `Dog` object using a class method.
Q16). What are static methods in Python?
Static methods do not access or modify class or instance state. They are defined using the `@staticmethod` decorator.
For example: `@staticmethod def is_valid_age(age): return age > 0` can be called without an instance or class reference.
Q17). What is multiple inheritance in Python?
Multiple inheritance allows a class to inherit from more than one parent class.
For example: `class FlyingDog(Dog, Bird):` means `FlyingDog` inherits from both `Dog` and `Bird`, combining their attributes and methods.
Q18). What is the diamond problem in multiple inheritance?
The diamond problem occurs when a class inherits from two classes that have a common base class, leading to ambiguity in method resolution. Python handles this with a method resolution order (MRO) to ensure consistent behavior.
Q19). What is the difference between `@staticmethod` and `@classmethod`?
`@staticmethod` methods do not access class or instance state and can be called on the class or instance. `@classmethod` methods access class state via `cls`.
For example: a `@staticmethod` might perform a utility function, while a `@classmethod` might modify or create class-level data.
Q20). What is the `__str__` method in Python?
The `__str__` method defines a readable string representation of an object.
For example: `def __str__(self): return f'Car(color={self.color}, make={self.make})'` makes `print(my_car)` output 'Car(color=red, make=Toyota)'.
Q21). What is the `__repr__` method in Python?
The `__repr__` method defines an unambiguous string representation of an object that can be used for debugging.
For example: `def __repr__(self): return f'Car(color={self.color}, make={self.make})'` helps developers understand the object's state.
Q22). What is the purpose of `__del__` method in Python?
The `__del__` method is called when an object is about to be destroyed. It is used to clean up resources.
For example: if a `FileHandler` class opens a file, `__del__` can ensure the file is closed when the object is deleted.
Q23). What are abstract classes in Python?
Abstract classes cannot be instantiated and are used to define a common interface for other classes. They are defined using the `ABC` module.
For example: `class Shape(ABC): @abstractmethod def area(self): pass` ensures that any subclass of `Shape` must implement `area()`.
Q24). What is the difference between an abstract class and an interface in Python?
Python uses abstract classes to achieve interface-like behavior. Abstract classes can have both abstract and concrete methods, whereas traditional interfaces in other languages only declare methods.
For example: an abstract class `Vehicle` might have a concrete method `start_engine()` and an abstract method `drive()`.
Q25). What is the `__init_subclass__` method?
The `__init_subclass__` method is called when a class is subclassed. It can be used to customize subclass behavior.
For example: you might use it to automatically register subclasses in a registry or enforce naming conventions.
Q26). What is the `@property` decorator in Python?
The `@property` decorator allows you to define methods that can be accessed like attributes.
For example: `@property def age(self): return self._age` allows you to access `age` as if it were a simple attribute while still using a method to calculate or retrieve its value.
Q27). What is the `__call__` method in Python?
The `__call__` method allows an object to be called like a function.
For example: if you define `def __call__(self, arg):`, you can create an object `func` that can be called with `func(arg)` to execute the code in `__call__`.
Q28). What are metaclasses in Python?
Metaclasses are classes of classes that define how classes behave.
For example: you can use a metaclass to automatically register new classes in a central registry. If `MyMeta` is a metaclass, you can define classes with `class MyClass(metaclass=MyMeta):`.
Q29). What is the `__mro__` attribute?
`__mro__` is an attribute that returns a tuple representing the method resolution order of a class. It shows the order in which base classes are looked up when searching for a method.
For example: `MyClass.__mro__` provides the order in which methods are inherited.
Q30). How does Python handle method resolution in multiple inheritance?
Python uses the C3 linearization algorithm to determine the method resolution order (MRO). This ensures a consistent and predictable method lookup order.
For example: if `A`, `B`, and `C` are base classes, Python determines the method resolution order based on the class hierarchy and inheritance.
Q31). What is composition in Python?
Composition involves building complex objects by combining simpler objects.
For example: a `Car` class might use an `Engine` class as a component. Instead of inheriting from `Engine`, `Car` would have an `Engine` instance as an attribute, allowing flexible changes and maintenance.
Q32). What is duck typing in Python?
Duck typing is a concept where the type or class of an object is determined by its behavior (methods and attributes) rather than its explicit type.
For example: if an object has a `quack()` method, it is treated as a duck, regardless of its actual class, as long as it behaves like a duck.
Q33). What are the advantages of using OOP in Python?
OOP provides advantages such as code reuse through inheritance, encapsulation of data and behavior, easier maintenance, and improved code organization.
For example: you can create a base class `Vehicle` and extend it with `Car` and `Bike` classes, reusing common functionality and enhancing code manageability.
Q34). What is the `__slots__` attribute?
`__slots__` is used to define a fixed set of attributes for a class, which can improve memory efficiency.
For example: if you define `__slots__ = ('name', 'age')` in a class, instances of that class can only have `name` and `age` attributes, reducing memory overhead.
Q35). How do you handle exceptions in OOP?
Exceptions in OOP are handled using try-except blocks. You can also define custom exceptions by inheriting from the `Exception` class.
For example: you might define `class CustomError(Exception): pass` to create a specific exception type, and handle it with `try...except CustomError as e:`.
Q36). What is a mixin class?
A mixin class is a class that provides methods to be used by other classes through inheritance. Mixins are typically used to add functionality to classes without being base classes themselves.
For example: a `LoggingMixin` class might provide logging capabilities that can be inherited by other classes to add logging functionality.
Q37). What is the `__contains__` method?
The `__contains__` method is used to check if an object contains a specific value. It is used by the `in` operator.
For example: if you have a class `MyContainer` with `def __contains__(self, item):`, you can use `item in my_container` to check if `item` is in `my_container`.
Q38). What is method chaining?
Method chaining allows you to call multiple methods on the same object in a single line.
For example: if you have methods `set_color(self, color)` and `set_size(self, size)`, you can chain them like `obj.set_color('red').set_size(10)` to apply both methods in one line, improving readability.
Q39). How do you implement a private method in Python?
Private methods in Python are indicated by a leading underscore (`_`).
For example: `_private_method()` is intended to be used only within the class and not from outside. Python does not enforce access control, but using underscores is a convention to indicate private methods.
Q40). What is the `__new__` method?
The `__new__` method is responsible for creating a new instance of a class. It is called before `__init__` and is used to control the creation of instances.
For example: `def __new__(cls):` can be used to create an instance, potentially altering instance creation behavior before initializing with `__init__`.
Q41). What is an example of a design pattern in Python?
One common design pattern is the Singleton pattern, which ensures that a class has only one instance.
For example: a `DatabaseConnection` class might use the Singleton pattern to ensure there is only one connection to the database throughout the application, avoiding unnecessary multiple connections.