How to inherit class in python
- User
How to inherit class in python
- Assistant
In Python, inheritance allows you to create a new class that inherits properties and methods from an existing class. The existing class is called the parent or base class, while the new class is called the child or derived class. Here's how to inherit from a class in Python:
-
Define the parent class: Create a class with the properties and methods you want to inherit. For example, let's create a
Personclass:class Person: def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname def printname(self): print(f"{self.firstname} {self.lastname}") -
Define the child class: Create a new class that inherits from the parent class. You can do this by listing the parent class in the
classstatement:class Student(Person): def __init__(self, firstname, lastname, age): Person.__init__(self, firstname, lastname) self.age = age def show_age(self): print(f"Age: {self.age}")In this example, the
Studentclass inherits from thePersonclass. -
Use the child class: Create an instance of the child class and call its methods:
harry = Student("Harry", "Potter", 15) harry.printname() # Output: Harry Potter harry.show_age() # Output: Age: 15
In this example, the
Studentclass inherits the properties and methods of thePersonclass, and we can access them through theharryobject.Note that if you want to inherit from multiple parent classes, Python supports multiple inheritance as well:
class Animal: def eat(self): print("I can eat") class Dog(Animal): def bark(self): print("Woof!") labrador = Dog() labrador.eat() # Output: I can eat labrador.bark() # Output: Woof!In this example, the
Dogclass inherits from theAnimalclass, and we can access the methods of both classes through thelabradorobject. -
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.