Inheritance Basics
Svep för att visa menyn
12345678910111213class Animal: def __init__(self, name): self.name = name def speak(self): return f"{self.name} makes a sound" class Dog(Animal): pass dog = Dog("Buddy") print(dog.name) # Output: Buddy print(dog.speak()) # Output: Buddy makes a sound
Inheritance allows you to create a new class (called a subclass) that is based on an existing class (called a base class or superclass). The subclass automatically inherits all the attributes and methods of the base class, so you do not have to rewrite code that is common to both classes. In the example above, the Animal class defines a constructor and a speak method. The Dog subclass inherits both from Animal. When you create an instance of Dog, you can access the name attribute and the speak method as if they were defined in Dog itself. This makes your code more reusable and organized, especially when you want to represent different types of objects that share common behaviors.
1234567891011class Dog(Animal): def fetch(self, item): return f"{self.name} fetches the {item}" def speak(self): base_sound = super().speak() return f"{base_sound}, but {self.name} barks!" dog = Dog("Buddy") print(dog.fetch("ball")) # Output: Buddy fetches the ball print(dog.speak()) # Output: Buddy makes a sound, but Buddy barks!
You can extend the functionality of a subclass by adding new methods or by overriding existing ones. In the revised Dog class, a new method called fetch is added, which is specific to dogs. The speak method is also overridden to provide a more specific implementation. To include behavior from the base class, you can use the super() function, which allows you to call methods from the superclass. This is useful when you want to enhance, not completely replace, the original method. Python determines which method to call using the method resolution order (MRO), which follows the inheritance chain from the subclass up to its ancestors.
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal