add a method to a subclass in python

To add a new method to a subclass you can define the method in the class definition of the subclass. The new method can then be called by instances of that subclass.

Here is an example of how to add a method to a subclass in Python:

main.py
class Person:
    def __init__(self, name):
        self.name = name
    
    def say_hello(self):
        print(f'Hello, my name is {self.name}')

class Student(Person):
    def study(self):
        print(f"{self.name} is studying")

# creating an instance of Student
s = Student('Sarah')
s.say_hello()  # method inherited from superclass
s.study()  # method added to subclass
378 chars
16 lines

In the code above, we define a superclass called Person that has a method called say_hello. We then define a subclass called Student that inherits from Person and adds a method called study. We create an instance of Student and call both methods, one inherited from the superclass and one defined in the subclass.

gistlibby LogSnag