0% found this document useful (0 votes)
12 views

OOPs

Oops

Uploaded by

vinay chappidi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

OOPs

Oops

Uploaded by

vinay chappidi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

1. What is Object-Oriented Programming (OOP)?

OOP is a programming paradigm based on the concept of objects, which


can contain data in the form of fields (attributes or properties) and code in
the form of procedures (methods). It promotes greater flexibility and
maintainability in programming through principles such as inheritance,
encapsulation, polymorphism, and abstraction.

2. What are the main principles of OOP?


The main principles are:
Encapsulation: Bundling of data with the methods that operate on that
data.
Inheritance: Mechanism where one class can inherit attributes and
methods from another class.
Polymorphism: Ability to present the same interface for differing
underlying data types.
Abstraction: Hiding complex implementation details and showing only
the necessary features of an object.

3. What is a class in Python?


A class in Python is a blueprint for creating objects. It defines a set of
attributes and methods that the created objects will have.

4. What is an object in Python?


An object is an instance of a class. It is a concrete entity based on the
class, with its own set of attributes and methods defined by the class.

5. What is a constructor in Python?


A constructor is a special method called `__init__` in Python, which is
automatically invoked when an object of the class is created. It is used to
initialize the object's attributes.
class MyClass:
def __init__(self, value):
self.value = value

6. What is a destructor in Python?


A destructor is a special method called `__del__`, which is called when an
object is about to be destroyed. It is used to clean up resources.

class MyClass:
def __del__(self):
print("Object is being destroyed")

7. What is inheritance in Python?


Inheritance is a mechanism where a new class (derived class) inherits
attributes and methods from an existing class (base class). It allows for
code reuse and the creation of a hierarchical relationship between classes.

class BaseClass:
def __init__(self):
self.base_attribute = "Base"

class DerivedClass(BaseClass):
def __init__(self):
super().__init__()
self.derived_attribute = "Derived"

8. What is the `super()` function?


The `super()` function in Python is used to call a method from the parent
class. It is commonly used to call the parent class constructor in the derived
class.
class BaseClass:
def __init__(self):
self.base_attribute = "Base"

class DerivedClass(BaseClass):
def __init__(self):
super().__init__()
self.derived_attribute = "Derived"

9. What is polymorphism in Python?


Polymorphism allows methods to do different things based on the object it
is acting upon. It can be achieved through method overriding and operator
overloading.
class Animal:
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"

10. What is encapsulation in Python?


Encapsulation is the bundling of data and methods that operate on that
data within a single unit (class). It also restricts direct access to some of an
object’s components, which is a means of preventing accidental
interference and misuse of the data.
class MyClass:
def __init__(self):
self._protected_attribute = "Protected"
self.__private_attribute = "Private"

def get_private_attribute(self):
return self.__private_attribute

11. What is abstraction in Python?


Abstraction is the concept of hiding the complex implementation details
and showing only the necessary features of an object. It is often achieved
using abstract classes and interfaces.

from abc import ABC, abstractmethod

class AbstractClass(ABC):
def abstract_method(self):
pass

class ConcreteClass(AbstractClass):
def abstract_method(self):
return "Concrete Implementation"

12. What is multiple inheritance?


Multiple inheritance is a feature in which a class can inherit attributes
and methods from more than one parent class.
class ClassA:
def method_a(self):
return "A"

class ClassB:
def method_b(self):
return "B"

class ClassC(ClassA, ClassB):


pass

c = ClassC()
print(c.method_a(), c.method_b()) # Output: A B

13. What are class and static methods?


Class methods: Defined using the `@classmethod` decorator. They take
`cls` as the first parameter and can modify the class state that applies
across all instances of the class.
class MyClass:
count = 0
def increment_count(cls):
cls.count += 1

Static methods: Defined using the `@staticmethod` decorator. They do


not take `self` or `cls` as the first parameter and cannot modify the class or
instance state.
class MyClass:
def static_method():
return "Static method called"

14. What is method overloading and method overriding?


Method overloading: Python does not support traditional method
overloading as in other languages, but it can be achieved through default
arguments or variable-length arguments.
class MyClass:
def method(self, a, b=0):
return a + b
Method overriding: Method overriding allows a derived class to provide a
specific implementation of a method already defined in its base class.
class BaseClass:
def method(self):
return "Base method"

class DerivedClass(BaseClass):
def method(self):
return "Derived method"

15. What is a Singleton design pattern?


The Singleton pattern ensures that a class has only one instance and
provides a global point of access to it.
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance

16. What is the difference between `__str__` and `__repr__` methods in


Python?
`__str__`: Intended to provide a “user-friendly” string representation of
an object. It’s meant to be readable and useful for end-users.
`__repr__`: Intended to provide a “developer-friendly” string
representation of an object. It’s meant to be unambiguous and, ideally, the
string returned by `__repr__` should be a valid Python expression that could
be used to recreate the object.

class MyClass:
def __init__(self, value):
self.value = value

def __str__(self):
return f'MyClass with value {self.value}'

def __repr__(self):
return f'MyClass({self.value})'

obj = MyClass(42)
print(str(obj)) # Output: MyClass with value 42
print(repr(obj)) # Output: MyClass(42)

17. What is the difference between `@staticmethod` and `@classmethod`


decorators in Python?
`@staticmethod`: A static method does not receive an implicit first
argument, either `self` or `cls`. It behaves like a plain function but belongs
to the class’s namespace.
`@classmethod`: A class method receives the class (`cls`) as the first
implicit argument. It can modify class state that applies across all instances
of the class.
class MyClass:
@staticmethod
def static_method():
return "Static method"
@classmethod
def class_method(cls):
return f"Class method of {cls.__name__}"
print(MyClass.static_method()) # Output: Static method
print(MyClass.class_method()) # Output: Class method of MyClass

18. Explain the concept of multiple inheritance in Python and potential


issues associated with it.
Multiple inheritance is when a class can inherit attributes and methods
from more than one parent class. This can lead to complexity and
ambiguity, particularly when the same attribute or method is inherited
from multiple base classes. The Method Resolution Order (MRO) in Python
helps to resolve these ambiguities by defining the order in which base
classes are searched when executing a method.
class A:
def method(self):
print("Method from class A")

class B:
def method(self):
print("Method from class B")

class C(A, B):


pass

c = C()
c.method() # Output: Method from class A (due to MRO)
print(C.mro()) # Output: [<class '__main__.C'>, <class '__main__.A'>,
<class '__main__.B'>, <class 'object'>]

19. What is a mixin, and how is it used in Python?


A mixin is a class that provides methods to other classes through
inheritance but is not intended to stand alone. Mixins are a way to compose
classes with reusable pieces of behavior. They are typically used to add
common functionality to multiple classes.
class LoggingMixin:
def log(self, message):
print(f"LOG: {message}")
class MyClass(LoggingMixin):
def do_something(self):
self.log("Doing something")
obj = MyClass()
obj.do_something() # Output: LOG: Doing something

20. What is a property in Python, and how do you define one?


A property in Python is a special kind of attribute that allows for the
customization of access to an attribute. Properties provide a way of using
getter, setter, and deleter methods without needing to call explicit methods.
It is defined using the `@property` decorator and can be used to add
validation logic to attribute access.
class MyClass:
def __init__(self, value):
self._value = value

@property
def value(self):
return self._value

@value.setter
def value(self, new_value):
if new_value < 0:
raise ValueError("Value cannot be negative")
self._value = new_value

obj = MyClass(10)
print(obj.value) # Output: 10
obj.value = 20 # Valid operation
print(obj.value) # Output: 20
obj.value = -5 # Raises ValueError: Value cannot be negative

You might also like