Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Python OOPs Interview Questions Day 1_ Master the Basics

Python 155 Coding Questions With Answers Python 155 Coding Questions With Answers Python 155 Coding Questions With Answers

Uploaded by

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

Python OOPs Interview Questions Day 1_ Master the Basics

Python 155 Coding Questions With Answers Python 155 Coding Questions With Answers Python 155 Coding Questions With Answers

Uploaded by

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

Python OOPS Interview

Questions:

1. How will you check if a class is a child of another class?

2. What is the __init__ method in Python?

3. Why is the __del__ method used?

4. How is an empty class created in Python?

5. Is it possible to call a parent class method without its instance


creation?
a. Using Class Method

b. Using Static Method

6. Are access specifiers used in Python?


a. Public

b. Protected

c. Private

7. How do you access parent members in the child class?


a. Using the super() function

8. What are Getter and Setter Functions in Python?


a. Why use Getters and Setters?

9. What is Method Overloading in Python?


a. Can you simulate overloading in Python?

Python OOPS Interview Questions: 1


b. Examples of Overloading using default arguments and args

10. What is Method Overriding in Python?


a. How does method overriding work?

b. Provide an example of method overriding.

11. What is the difference between Overloading and Overriding in


Python?

1. How will you check if a class is a child of another class?


You can check if a class is a child of another class using the issubclass() function
in Python.

Syntax: issubclass(child_class, parent_class)

Returns True if the child class is a subclass of the parent class, and False

otherwise.

Example:

class Parent:
pass

class Child(Parent):
pass

Python OOPS Interview Questions: 2


print(issubclass(Child, Parent)) # Output: True

2. What is the __init__ method in Python?


The __init__ method is a special method in Python classes. It is called a
constructor and is used to initialize the attributes of an object when it is
created.

It is automatically invoked when a new object of the class is instantiated.


Syntax:

class MyClass:
def __init__(self, param1, param2):
self.param1 = param1
self.param2 = param2
print(self.param1)

# Create an object of MyClass and pass values to the const


ructor
obj = MyClass(10, 20)

Example:

class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed

dog1 = Dog("Buddy", "Golden Retriever")


print(dog1.name) # Output: Buddy

Python OOPS Interview Questions: 3


print(dog1.breed) # Output: Golden Retriever

3. Why is finalize() used?


is used in Python to implement finalization for objects, which is
finalize()

often used for resource cleanup or performing certain tasks before an object
is destroyed.

It is typically part of the garbage collection process, invoked by Python when


an object is about to be destroyed.

In Python, the __del__() method can be used for finalization.


Example:

class Resource:
def __del__(self):
print("Resource is being deleted")

obj = Resource()
del obj

Method: The __del__ method is a destructor in Python that is


__del__

automatically called when an object is about to be destroyed (garbage


collected). In this case, when del obj is called, the __del__ method is invoked,
and the message "Resource is being deleted" is printed.

del obj : This explicitly deletes the reference to obj . In Python, objects are
garbage collected when there are no references left to them. Calling del

removes the reference, triggering the __del__ method if the object is no longer
in use.

Python OOPS Interview Questions: 4


5. How is an empty class created in Python?
An empty class in Python can be created using the class keyword with no
attributes or methods defined inside it.
Example:

class EmptyClass:
pass

The pass keyword is used when you need a placeholder but don't want to
write any code yet.

6. Is it possible to call a parent class without its instance


creation?
Yes, it is possible to call a method or access a class member of the parent class
without creating an instance by using the class itself.

You can use ClassName.method() to call a method directly from the class.

This can be achieved using class methods or static methods.

1. Using Class Method:


A class method is a method that is bound to the class and not the instance. It
takes the class itself as its first argument (usually named cls ).

Example of Class Method:

class Parent:
@classmethod
def class_method(cls):
print("This is a class method of the Parent class.")

class Child(Parent):

Python OOPS Interview Questions: 5


pass

# Calling class method directly from the Parent class


Parent.class_method()

# Alternatively, calling class method from the Child class (s


ince it's inherited)
Child.class_method()

2. Using Static Method:


A static method is a method that doesn't take self or cls as its first argument. It
is not bound to the class or the instance, so it can be called without creating an
object.

Example of Static Method:

class Parent:
@staticmethod
def static_method():
print("This is a static method of the Parent class.")

class Child(Parent):
pass

# Calling static method directly from the Parent class


Parent.static_method()

# Alternatively, calling static method from the Child class


(since it's inherited)
Child.static_method()

7. Are access specifiers used in Python?

Python OOPS Interview Questions: 6


Python does not have explicit access specifiers like private , protected , and public

as in other languages. Instead, it uses naming conventions:

Public: Attributes and methods without any leading underscore ( variable ).

Protected: Attributes and methods with a single leading underscore


( _variable ), indicating that they should not be accessed directly outside the
class.

Private: Attributes and methods with a double leading underscore ( __variable ),


which triggers name mangling.

Example:

class MyClass:
def __init__(self):
self.public = 1 # Public attribute
self._protected = 2 # Protected attribute (con
vention)
self.__private = 3 # Private attribute (name
mangling)

def get_private(self):
return self.__private # Method to access private
attribute

# Create an instance of MyClass


obj = MyClass()

# Access public attribute directly


print(obj.public) # Output: 1

# Access protected attribute directly (not recommended, bu


t possible)
print(obj._protected) # Output: 2

# Access private attribute directly (this will cause an er

Python OOPS Interview Questions: 7


ror)
# print(obj.__private) # Uncommenting this will raise an
AttributeError

# Access private attribute using a getter method


print(obj.get_private()) # Output: 3

# Access private attribute with name mangling (not recomme


nded)
print(obj._MyClass__private) # Output: 3

8. How do you access parent members in the child class?


To access parent class members (attributes or methods) in a child class:

You can directly use super() to call methods or access attributes of the parent
class.

Example:

class Parent:
def __init__(self):
self.name = "Parent"

def greet(self):
print("Hello from Parent!")

class Child(Parent):
def __init__(self):
super().__init__() # Calling parent class's __ini
t__
print(f"Child Name: {self.name}")

Python OOPS Interview Questions: 8


child = Child() # Output: Child Name: Parent

What Are Getter and Setter Functions?


In object-oriented programming, getter and setter methods are used to access
and modify the values of private or protected attributes in a class.

Getter: A method used to get (or retrieve) the value of a private or protected
attribute.

Setter: A method used to set (or modify) the value of a private or protected
attribute.

In Python, getter and setter methods are typically used to encapsulate and protect
class data while still allowing controlled access to those attributes.

Why Use Getters and Setters?


Encapsulation: To control the access to an attribute. By using getter and
setter methods, you can perform validation or processing before getting or
setting the attribute's value.

Control: You can impose constraints or rules when setting an attribute's value,
like ensuring a positive number for a salary.

Code Example: Getter and Setter Functions

python
Copy code
class MyClass:
def __init__(self):
self.__name = "John"
self.__age = 25

# Getter method for 'name'


def get_name(self):

Python OOPS Interview Questions: 9


return self.__name

# Setter method for 'name'


def set_name(self, name):
self.__name = name

# Getter method for 'age'


def get_age(self):
return self.__age

# Setter method for 'age' with validation


def set_age(self, age):
if age > 0: # Ensure age is positive
self.__age = age
else:
print("Age must be positive")

# Create an object of MyClass


obj = MyClass()

# Access attributes using getter methods


print("Name:", obj.get_name()) # Output: Name: John
print("Age:", obj.get_age()) # Output: Age: 25

# Modify attributes using setter methods


obj.set_name("Alice")
obj.set_age(30)

# Access modified values using getter methods


print("Updated Name:", obj.get_name()) # Output: Updated Nam
e: Alice
print("Updated Age:", obj.get_age()) # Output: Updated Ag
e: 30

Python OOPS Interview Questions: 10


# Attempt to set an invalid age
obj.set_age(-5) # Output: Age must be positive

1. Overloading in Python (Achieved Using Default Arguments or


args / *kwargs )
In languages like Java, you can define multiple methods with the same name but
with different arguments. In Python, this concept is not natively supported, but you
can simulate it using default arguments or variable-length arguments ( *args and
**kwargs ).

Example of "Overloading" in Python using default arguments:

python
Copy code
class Calculator:
def add(self, a, b=0): # Default value for b is 0, so th
is simulates overloading
return a + b

calc = Calculator()

# Adding two numbers


print(calc.add(2, 3)) # Output: 5

# Adding one number (b is defaulted to 0)


print(calc.add(2)) # Output: 2

Example of "Overloading" using args :

python
Copy code
class Calculator:

Python OOPS Interview Questions: 11


def add(self, *args): # *args allows multiple arguments
return sum(args)

calc = Calculator()

print(calc.add(2, 3)) # Output: 5


print(calc.add(1, 2, 3, 4)) # Output: 10

Key Points about Overloading:


Python does not support method overloading in the traditional sense.

You can simulate overloading using default parameters or args / *kwargs .

2. Overriding in Python
Overriding happens when a method in the child class has the same name, same
number of parameters, and same signature as a method in the parent class. The
method in the child class "overrides" the one in the parent class, meaning that
when you call the method on the child class, it uses the method from the child
class.

Example of Overriding in Python:

python
Copy code
class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal):
def speak(self): # Overriding the speak method from Anim
al class
print("Dog barks")

# Creating an instance of Dog

Python OOPS Interview Questions: 12


dog = Dog()
dog.speak() # Output: Dog barks

Example where method is overridden:


In this example, the speak method of the Dog class overrides the speak method
in the Animal class. When we call dog.speak() , it prints "Dog barks" instead of
"Animal speaks", even though the speak method exists in both the parent and
child classes.

Key Points about Overriding:


Overriding is a concept in object-oriented programming where a child class
provides a specific implementation of a method that is already defined in its
parent class.

The child class method has the same name, parameters, and signature as the
parent class method.

The method in the child class "overrides" the parent class method when called
on an instance of the child class.

Summary of Differences:
Feature Overloading Overriding

Defining multiple methods with A child class method has the same
Definition the same name but different name and parameters as the parent
parameters. class method and overrides it.

Not directly supported. Achieved


Support in Supported in Python. Child method
using default arguments or
Python overrides parent method.
*args / **kwargs .

Allows defining different


Allows customizing or modifying the
Purpose behaviors based on input
inherited behavior of a method.
arguments.

Method There is no method resolution Parent class method is replaced by


Resolution order like in overriding. You get a the child class method when the
single method signature.

Python OOPS Interview Questions: 13


method is called on the child class
object.

9. How does inheritance work in Python? Explain it with an


example.
Inheritance allows a new class (child class) to inherit attributes and methods
from an existing class (parent class).

The child class can override the methods of the parent class, or it can add its
own methods and attributes.

Example:

class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal): # Inherits from Animal class


def speak(self): # Overrides speak method
print("Dog barks")

dog = Dog()
dog.speak() # Output: Dog barks

The Dog class inherits from Animal and overrides the speak() method.

3. What is polymorphism in Python?


Polymorphism means having the same method name but different
implementations in different classes. It allows objects of different classes to be

Python OOPS Interview Questions: 14


treated as instances of the same class through a common interface.

Example:

python
Copy code
class Dog:
def sound(self):
return "Bark"

class Cat:
def sound(self):
return "Meow"

def make_sound(animal):
print(animal.sound())

dog = Dog()
cat = Cat()

make_sound(dog) # Output: Bark


make_sound(cat) # Output: Meow

4. What is encapsulation in Python?


Encapsulation is the concept of restricting direct access to some of an
object's components and protecting its internal state by using access
modifiers like public, protected, and private.

In Python, this is achieved by using a leading underscore ( _ ) for protected


attributes and a double leading underscore ( __ ) for private attributes.

Example:

python
Copy code

Python OOPS Interview Questions: 15


class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute

def get_balance(self):
return self.__balance

account = BankAccount(1000)
print(account.get_balance()) # Output: 1000

5. What are the types of inheritance in Python?


There are several types of inheritance in Python:

Single Inheritance: A child class inherits from one parent class.

Multiple Inheritance: A child class inherits from more than one parent class.

Multilevel Inheritance: A child class inherits from a class which itself is


derived from another class.

Hierarchical Inheritance: Multiple child classes inherit from a single parent


class.

Hybrid Inheritance: A combination of two or more types of inheritance.

Example (Multiple Inheritance):

python
Copy code
class Parent1:
def speak(self):
print("Hello from Parent1")

class Parent2:
def greet(self):
print("Greetings from Parent2")

Python OOPS Interview Questions: 16


class Child(Parent1, Parent2):
pass

c = Child()
c.speak() # Output: Hello from Parent1
c.greet() # Output: Greetings from Parent2

6. What is method resolution order (MRO)?


MRO is the order in which Python looks for a method in a class hierarchy. In
case of multiple inheritance, the MRO determines which method will be called
first. It follows the C3 Linearization algorithm.

Example:

python
Copy code
class A:
def method(self):
print("A method")

class B(A):
def method(self):
print("B method")

class C(A):
def method(self):
print("C method")

class D(B, C):


pass

d = D()

Python OOPS Interview Questions: 17


d.method() # Output: B method (MRO: D -> B -> C -> A)

7. Explain the super() function in Python.


The super() function in Python is used to call a method from the parent class.
It allows the child class to invoke methods from the parent class, especially in
the case of multiple inheritance.

Example:

python
Copy code
class Parent:
def greet(self):
print("Hello from Parent!")

class Child(Parent):
def greet(self):
super().greet() # Call parent class's greet method
print("Hello from Child!")

child = Child()
child.greet() # Output: Hello from Parent! \n Hello from Chi
ld!

8. What is self in Python?


self is a reference to the current instance of the class. It is automatically
passed to the instance methods and is used to access the instance's
attributes and methods.

Example:

Python OOPS Interview Questions: 18


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

def display(self):
print(self.value)

obj = MyClass(10)
obj.display() # Output: 10

9. What is the purpose of __str__() method?


The __str__() method is used to define a human-readable string
representation of an object. It is called by the print() function to display the
object's information.

Example:

python
Copy code
class Dog:
def __init__(self, name):
self.name = name

def __str__(self):
return f"My dog's name is {self.name}"

dog = Dog("Buddy")
print(dog) # Output: My dog's name is Buddy

Python OOPS Interview Questions: 19


10. What is __repr__() method used for?

python
Copy code
- The `__repr__()` method is used to define an official strin
g representation of an object that is meant for debugging and
development. It provides a string that can ideally be used to
recreate the object.

**Example**:
```python
class Dog:
def __init__(self, name):
self.name = name

def __repr__(self):
return f"Dog(name={self.name!r})"

dog = Dog("Buddy")
print(repr(dog)) # Output: Dog(name='Buddy')
```

11. What is an abstract class in Python?

python
Copy code
- An **abstract class** is a class that cannot be instantiate
d. It serves as a blueprint for other classes. Abstract class
es are defined using the `ABC` module and `abstractmethod` de
corator.

**Example**:
```python
from abc import ABC, abstractmethod

Python OOPS Interview Questions: 20


class Animal(ABC):
@abstractmethod
def sound(self):
pass

class Dog(Animal):
def sound(self):
return "Bark"

dog = Dog()
print(dog.sound()) # Output: Bark
```

12. What is the difference between is and == in Python?

python
Copy code
- `is`: Checks if two references point to the same object (me
mory location).
- `==`: Checks if the values of two objects are equal.

**Example**:
```python
a = [1, 2, 3]
b = [1, 2, 3]

print(a == b) # Output: True (values are equal)


print(a is b) # Output: False (different objects)
```

13. Can Python have multiple constructors?

Python OOPS Interview Questions: 21


python
Copy code
- Python does not support multiple constructors directly. How
ever, you can simulate multiple constructors using default ar
guments or class methods.

**Example**:
```python
class MyClass:
def __init__(self, x=None):
if x is None:
self.value = 0
else:
self.value = x

obj1 = MyClass() # Uses default constructor


obj2 = MyClass(10) # Uses constructor with value
```

14. What are static methods in Python?

python
Copy code
- A **static method** is a method that belongs to the class r
ather than the instance. It cannot modify the object or class
state. Static methods are defined using the `@staticmethod` d
ecorator.

**Example**:
```python
class Math:
@staticmethod
def add(x, y):

Python OOPS Interview Questions: 22


return x + y

print(Math.add(5, 3)) # Output: 8


```

15. What are class methods in Python?

python
Copy code
- A **class method** is a method that is bound to the class a
nd not the instance. It takes the class as its first argument
(`cls`) and is defined using the `@classmethod` decorator.

**Example**:
```python
class MyClass:
count = 0

@classmethod
def increment(cls):
cls.count += 1

MyClass.increment()
print(MyClass.count) # Output: 1
```

16. What is the difference between del and remove() in Python?

less
Copy code
- `del`: Deletes a variable or an item at a specific index in
a list.

Python OOPS Interview Questions: 23


- `remove()`: Removes the first occurrence of a specified val
ue from a list.

**Example**:
```python
lst = [1, 2, 3, 4]
del lst[0] # Removes the first element
print(lst) # Output: [2, 3, 4]

lst.remove(3) # Removes the value 3


print(lst) # Output: [2, 4]
```

17. How do you create a class method?

kotlin
Copy code
- To create a **class method**, use the `@classmethod` decora
tor and define the method to take `cls` as the first argumen
t.

**Example**:
```python
class Person:
@classmethod
def from_string(cls, info):
name, age = info.split(",")
return cls(name, int(age))

person = Person.from_string("John,30")
```

Python OOPS Interview Questions: 24


18. What are class attributes and instance attributes in Python?
Class attributes are attributes that are shared among all instances of a class.
They are defined within the class but outside any method.

Instance attributes are attributes that are specific to an instance of the class.
They are usually defined in the __init__() method.

Example:

python
Copy code
class Car:
wheels = 4 # Class attribute

def __init__(self, brand):


self.brand = brand # Instance attribute

car1 = Car("Toyota")
car2 = Car("Honda")
print(car1.wheels) # Output: 4 (Class attribute)
print(car2.brand) # Output: Honda (Instance attribute)

19. What are the __new__() and __init__() methods in Python?


: It is the method that creates a new instance of a class. It is called
__new__()

before __init__() and is responsible for creating a new object.

__init__() : It is the method that initializes the object after it has been created.
It is called after __new__() and sets the initial state of the object.

Example:

class MyClass:
def __new__(cls):
print("Creating instance")

Python OOPS Interview Questions: 25


return super().__new__(cls)

def __init__(self):
print("Initializing instance")

obj = MyClass()
# Output:
# Creating instance
# Initializing instance

1. Overloading in Python (Achieved Using Default Arguments or


args / *kwargs )
In languages like Java, you can define multiple methods with the same name but
with different arguments. In Python, this concept is not natively supported, but you
can simulate it using default arguments or variable-length arguments ( *args and
**kwargs ).

Example of "Overloading" in Python using default arguments:

python
Copy code
class Calculator:
def add(self, a, b=0): # Default value for b is 0, so th
is simulates overloading
return a + b

calc = Calculator()

# Adding two numbers


print(calc.add(2, 3)) # Output: 5

# Adding one number (b is defaulted to 0)

Python OOPS Interview Questions: 26


print(calc.add(2)) # Output: 2

Example of "Overloading" using args :

python
Copy code
class Calculator:
def add(self, *args): # *args allows multiple arguments
return sum(args)

calc = Calculator()

print(calc.add(2, 3)) # Output: 5


print(calc.add(1, 2, 3, 4)) # Output: 10

Key Points about Overloading:


Python does not support method overloading in the traditional sense.

You can simulate overloading using default parameters or args / *kwargs .

2. Overriding in Python
Overriding happens when a method in the child class has the same name, same
number of parameters, and same signature as a method in the parent class. The
method in the child class "overrides" the one in the parent class, meaning that
when you call the method on the child class, it uses the method from the child
class.

Example of Overriding in Python:

python
Copy code
class Animal:

Python OOPS Interview Questions: 27


def speak(self):
print("Animal speaks")

class Dog(Animal):
def speak(self): # Overriding the speak method from Anim
al class
print("Dog barks")

# Creating an instance of Dog


dog = Dog()
dog.speak() # Output: Dog barks

Example where method is overridden:


In this example, the speak method of the Dog class overrides the speak method
in the Animal class. When we call dog.speak() , it prints "Dog barks" instead of
"Animal speaks", even though the speak method exists in both the parent and
child classes.

Key Points about Overriding:


Overriding is a concept in object-oriented programming where a child class
provides a specific implementation of a method that is already defined in its
parent class.

The child class method has the same name, parameters, and signature as the
parent class method.

The method in the child class "overrides" the parent class method when called
on an instance of the child class.

Python OOPS Interview Questions: 28

You might also like