Oop Lab
Oop Lab
def sound(self):
print(f"{self.name} makes a sound.")
• Animal is the parent class.
• It has an attribute (name) and a method (sound()).
3. Code Reusability
By inheriting from a parent class, we can reuse the existing code. For example, instead
of writing a new class from scratch for Dog, we reused the Animal class and only added
the parts specific to Dog.
4. Method Overriding
A child class can override methods from the parent class. This means the child class
can provide its own version of a method that’s already defined in the parent class.
In the Dog class, we override the sound() method:
python
Copy code
class Dog(Animal):
def sound(self):
print(f"{self.name} barks.") # New behavior for Dog class
6. Full Example
python
Copy code
class Animal:
def __init__(self, name):
self.name = name
def sound(self):
print(f"{self.name} makes a sound.")
class Dog(Animal):
def sound(self):
print(f"{self.name} barks.")
class Cat(Animal):
def sound(self):
print(f"{self.name} meows.")
# Creating instances
dog = Dog("Buddy")
cat = Cat("Whiskers")
def sound(self):
print(f"{self.name} makes a sound.")
# Child class that inherits from Animal, but does NOT override the sound() method
class Dog(Animal):
pass