Python OOPs Interview Questions Day 1_ Master the Basics
Python OOPs Interview Questions Day 1_ Master the Basics
Questions:
b. Protected
c. Private
Returns True if the child class is a subclass of the parent class, and False
otherwise.
Example:
class Parent:
pass
class Child(Parent):
pass
class MyClass:
def __init__(self, param1, param2):
self.param1 = param1
self.param2 = param2
print(self.param1)
Example:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
often used for resource cleanup or performing certain tasks before an object
is destroyed.
class Resource:
def __del__(self):
print("Resource is being deleted")
obj = Resource()
del obj
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.
class EmptyClass:
pass
The pass keyword is used when you need a placeholder but don't want to
write any code yet.
You can use ClassName.method() to call a method directly from the class.
class Parent:
@classmethod
def class_method(cls):
print("This is a class method of the Parent class.")
class Child(Parent):
class Parent:
@staticmethod
def static_method():
print("This is a static method of the Parent class.")
class Child(Parent):
pass
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
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}")
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.
Control: You can impose constraints or rules when setting an attribute's value,
like ensuring a positive number for a salary.
python
Copy code
class MyClass:
def __init__(self):
self.__name = "John"
self.__age = 25
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()
python
Copy code
class Calculator:
calc = Calculator()
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.
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")
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.
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")
dog = Dog()
dog.speak() # Output: Dog barks
The Dog class inherits from Animal and overrides the speak() method.
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()
Example:
python
Copy code
def get_balance(self):
return self.__balance
account = BankAccount(1000)
print(account.get_balance()) # Output: 1000
Multiple Inheritance: A child class inherits from more than one parent class.
python
Copy code
class Parent1:
def speak(self):
print("Hello from Parent1")
class Parent2:
def greet(self):
print("Greetings from Parent2")
c = Child()
c.speak() # Output: Hello from Parent1
c.greet() # Output: Greetings from Parent2
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")
d = D()
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!
Example:
def display(self):
print(self.value)
obj = MyClass(10)
obj.display() # Output: 10
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
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')
```
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
class Dog(Animal):
def sound(self):
return "Bark"
dog = Dog()
print(dog.sound()) # Output: Bark
```
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]
**Example**:
```python
class MyClass:
def __init__(self, x=None):
if x is None:
self.value = 0
else:
self.value = x
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
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
```
less
Copy code
- `del`: Deletes a variable or an item at a specific index in
a list.
**Example**:
```python
lst = [1, 2, 3, 4]
del lst[0] # Removes the first element
print(lst) # Output: [2, 3, 4]
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")
```
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
car1 = Car("Toyota")
car2 = Car("Honda")
print(car1.wheels) # Output: 4 (Class attribute)
print(car2.brand) # Output: Honda (Instance attribute)
__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")
def __init__(self):
print("Initializing instance")
obj = MyClass()
# Output:
# Creating instance
# Initializing instance
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()
python
Copy code
class Calculator:
def add(self, *args): # *args allows multiple arguments
return sum(args)
calc = Calculator()
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.
python
Copy code
class Animal:
class Dog(Animal):
def speak(self): # Overriding the speak method from Anim
al class
print("Dog barks")
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.