OOPS Python
OOPS Python
# Creating an Object
object_name = ClassName(value1, value2)
# Calling a Method
object_name.display()
Inheritance in Python
1. What is Inheritance?
Inheritance is one of the fundamental concepts of Object-Oriented
Programming (OOP). It allows a class (child class) to inherit attributes and
methods from another class (parent class). This helps in code reusability and
reducing redundancy.
Output:
Animal makes a sound
Dog barks!
# Parent Class 2
class Wheels:
def rotate(self):
print("Wheels are rotating")
Output:
Engine started
Wheels are rotating
Car is moving
Output:
Breathing...
Eating...
Barking...
# Child Class 2
class Bike(Vehicle):
def ride(self):
print("Bike is riding")
Output:
Vehicle is moving
Car is driving
Vehicle is moving
Bike is riding
# Creating an object of D
obj = D()
obj.method_A() # Inherited from A
obj.method_B() # Inherited from B
obj.method_C() # Inherited from C
obj.method_D() # From D
Output:
Method from class A
Method from class B
Method from class C
Method from class D
5. Method Overriding in Inheritance
If a child class has the same method as the parent class, the child class method
overrides the parent’s method.
class Animal:
def sound(self):
print("Animals make sound")
class Dog(Animal):
def sound(self): # Overriding the parent class method
print("Dog barks!")
dog = Dog()
dog.sound() # Calls the overridden method in the child class
Output:
Dog barks!
class Child(Parent):
def show(self):
super().show() # Calls the parent class method
print("This is the Child class")
obj = Child()
obj.show()
Output:
This is the Parent class
This is the Child class
# Abstract Class
class Vehicle(ABC):
@abstractmethod
def start(self):
pass # Abstract method (must be implemented in child class)
@abstractmethod
def stop(self):
pass # Abstract method (must be implemented in child class)
def stop(self):
print("Car stops when brakes are applied")
# Creating an object of Car
car = Car()
car.start()
car.stop()
________________________________________
5. Explanation
Concept Description
Abstract Class Defines abstract methods start() and stop() but does not
(Vehicle) implement them.
# Abstract Class
class ATM(ABC):
@abstractmethod
def withdraw(self, amount):
pass
@abstractmethod
def deposit(self, amount):
pass
# Concrete Class
class BankATM(ATM):
def withdraw(self, amount):
print(f"Withdrew ${amount} from the ATM")
Output:
Deposited $500 into the ATM
Withdrew $200 from the ATM
def display(self):
print(f"{self.brand} {self.model}")
2. What is an object in Python?
• Answer: An object is an instance of a class.
• Example:
my_car = Car("Tesla", "Model S")
my_car.display() # Output: Tesla Model S
class Dog(Animal):
def bark(self):
print("Dog barks")
dog = Dog()
dog.speak() # Output: Animal speaks
dog.bark() # Output: Dog barks
class Dog(Animal):
def speak(self):
print("Dog barks")
dog = Dog()
dog.speak() # Output: Dog barks
class Dog:
def speak(self):
print("Bark")
def animal_sound(animal):
animal.speak()
def get_balance(self):
return self.__balance
class Person:
def __init__(self, name):
self.__name = name
def get_name(self):
return self.__name
p = Person("Alice")
print(p.get_name()) # Output: Alice
# print(p.__name) # Error: AttributeError
def __init__(self):
print("Initializing instance")
obj = MyClass()
@classmethod
def increment_count(cls):
cls.count += 1
MyClass.increment_count()
print(MyClass.count) # Output: 1
calc = Calculator()
calc.add(5).multiply(2)
print(calc.value) # Output: 10
class Child(Parent):
def greet(self):
super().greet()
print("Hello from Child")
c = Child()
c.greet()
# Output:
# Hello from Parent
# Hello from Child
class A:
def greet(self):
print("Hello from A")
class B:
def greet(self):
print("Hello from B")
c = C()
c.greet() # Output: Hello from A (due to method resolution order)
class B(A):
pass
class C(A):
pass
def __str__(self):
return f"Person: {self.name}"
p = Person("Alice")
print(p) # Output: Person: Alice
def __repr__(self):
return f"Person(name='{self.name}')"
p = Person("Alice")
print(repr(p)) # Output: Person(name='Alice')
19. What is the difference between __str__ and __repr__?
• Answer:
o __str__: User-friendly string representation.
o __repr__: Unambiguous string representation for debugging.
obj = MyClass()
del obj # Output: Object destroyed
add = Adder()
print(add(2, 3)) # Output: 5
def __len__(self):
return len(self.items)
def __iter__(self):
return iter(range(self.start, self.end))
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3.x, p3.y) # Output: 4 6
p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1 == p2) # Output: True
def __hash__(self):
return hash(self.name)
p = Person("Alice")
print(hash(p))
30. What is the __slots__ attribute?
• Answer: The __slots__ attribute restricts the creation of new attributes
in an object, saving memory.
• Example:
class Person:
__slots__ = ['name', 'age']
p = Person("Alice", 25)
# p.address = "123 Street" # Error: AttributeError