CodeCraft Innovation
The belief that complex systems require armies of designers and programmers is wrong. A system that is not understood in its entirety, or at least to a significant degree of detail by a single individual, should probably not be built.
*Now, let's move to the next topic in the Python Learning Series*
*Inheritance and Polymorphism*
*What is Inheritance?*
Inheritance is an important concept in Object-Oriented Programming (OOP). It allows one class to inherit the properties and methods of another class. This helps us create a hierarchy of classes, where a base class (or parent class) is extended by one or more derived classes (child classes).
In simple terms, inheritance lets you reuse code by creating new classes based on existing ones.
*Real-World Example:*
Imagine you have a parent class called Animal and two child classes: Dog and Cat. The Dog and Cat classes inherit properties from the Animal class (like a name and age), and they can also add their specific behaviors (like bark for Dog and meow for Cat).
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
return "Animal sound"
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# Creating objects
dog = Dog("Buddy", 3)
cat = Cat("Whiskers", 2)
print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow!
*In the above example:*
The Animal class is the parent (or base) class.
Dog and Cat are child classes that inherit from Animal.
Both the Dog and Cat classes override the speak() method from Animal to provide specific behavior for each.
*What is Polymorphism?*
Polymorphism is another key concept in OOP that allows one method to behave differently based on the object it is acting upon. In simple terms, polymorphism means that you can call the same method on different objects, but each object may respond in its own way.
*Real-World Example:* In the case of our Animal classes, both Dog and Cat have a speak() method. Although the method name is the same, the implementation is different for each class (a dog barks and a cat meows).
# The same method name, but different behavior
def animal_sound(animal):
print(animal.speak())
# Calling polymorphism
animal_sound(dog) # Output: Woof!
animal_sound(cat) # Output: Meow!
*In the above example:*
The animal_sound() function calls the speak() method.
Depending on whether the object passed is a Dog or a Cat, it behaves differently.
This is an example of method overriding (a form of polymorphism).
*Types of Polymorphism in Python:*
*1. Method Overloading:* Python doesn’t support method overloading directly (i.e., defining multiple methods with the same name but different parameters), but you can achieve this by using default parameters or variable-length arguments.
class Example:
def greet(self, name="Guest"):
return f"Hello, {name}!"
obj = Example()
print(obj.greet()) # Output: Hello, Guest!
print(obj.greet("Alice")) # Output: Hello, Alice!
*2. Method Overriding:* As demonstrated earlier, method overriding occurs when a child class provides its own version of a method that is already defined in the parent class.
*How Inheritance and Polymorphism Work Together:*
Inheritance and polymorphism often work hand-in-hand in OOP. Inheritance allows a child class to inherit methods from a parent class, while polymorphism allows the child class to modify (or override) those methods.
class Animal:
def sound(self):
return "Some generic sound"
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
# Create objects
animals = [Dog(), Cat()]
# Demonstrating polymorphism
for animal in animals:
print(animal.sound())
*Output:*
Woof!
Meow!
Here, even though both Dog and Cat are calling the same method (sound()), they respond differently. This is polymorphism in action, where the same method behaves differently based on the object.
*Key Takeaways:*
Inheritance allows a class to inherit attributes and methods from another class. This helps in code reuse and creating class hierarchies.
Polymorphism allows methods to behave differently based on the object it is called on. This helps create more flexible and extensible code.
*Common Interview Questions on Inheritance and Polymorphism:*
1. Explain inheritance and polymorphism in Python with examples.
2. What is method overriding? Can you give an example?
3. Can you explain multiple inheritance and its potential issues in Python?
4. How does polymorphism help in making a program more flexible?
5. What is the difference between a parent class and a child class?
6. How would you handle method overloading in Python
Let's now move to the next important topic in the Python Learning Series
*File Handling in Python*
*What is File Handling?*
File handling allows Python to read from and write to files—text files, CSVs, logs, etc.
It’s used in almost every real-world project: whether it's storing user data, reading configurations, or writing logs.
*Basic File Operations:*
*1. Open a file*
file = open("example.txt", "r") # 'r' for read mode
*2. Read from a file*
content = file.read()
print(content)
*3. Write to a file*
file = open("example.txt", "w") # 'w' for write mode
file.write("Hello, Python!")
file.close()
*4. Append to a file*
file = open("example.txt", "a") # 'a' for append mode
file.write("\nNew Line")
*5. Close the file*
file.close()
*Better Practice: Using with statement*
with open("example.txt", "r") as file:
content = file.read()
print(content)
This automatically closes the file after you're done reading or writing.
*Modes to Remember:*
- 'r' – read
- 'w' – write (overwrites)
- 'a' – append
- 'r+' – read & write
File handling is commonly tested in interviews and very useful in automation scripts and data processing tasks.
Click here to claim your Sponsored Listing.
Category
Telephone
Website
Address
Blantyre