Inheritance in Python
Inheritance is a way to create new classes that are based on existing classes, inheriting their attributes and behaviors. Here's an example of defining a subclass that inherits from a superclass:
python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow"
dog = Dog("Fido")
cat = Cat("Whiskers")
print(dog.name + ": " + dog.speak())
print(cat.name + ": " + cat.speak())
In this example, we define a superclass called Animal that has one instance variable, name, and one abstract method, speak, that does not have an implementation. We then define two subclasses, Dog and Cat, that inherit from Animal and provide their own implementation of the speak method.
We create one instance of each subclass, dog and cat, and call their speak method. The Dog instance will return the string "Woof!", and the Cat instance will return "Meow". We concatenate these strings with the animal's name and print them to the console.
No comments:
Post a Comment