In Python, how do you create a Python subclass from a superclass?

In Python, how do you create a Python subclass from a superclass?

You can create a Python subclass by defining a new class and passing the superclass as a parameter. The subclass inherits methods and attributes from the superclass.

class Superclass:
    def greet(self):
        print("Hello from Superclass!")

class Subclass(Superclass):
    pass

obj = Subclass()
obj.greet()  # Output: Hello from Superclass!

A Python subclass can override methods from the superclass to change their behavior.

class Superclass:
    def greet(self):
        print("Hello from Superclass!")

class Subclass(Superclass):
    def greet(self):
        print("Hello from Subclass!")

obj = Subclass()
obj.greet()  # Output: Hello from Subclass!

You can use the super() function in the Python subclass to call methods from the superclass. This is useful if you want to extend the behavior of the superclass method rather than completely overriding it.

class Superclass:
    def greet(self):
        print("Hello from Superclass!")

class Subclass(Superclass):
    def greet(self):
        super().greet()  # Calling the superclass method
        print("Hello from Subclass!")

obj = Subclass()
obj.greet()  

Output:

Hello from Superclass!

Hello from Subclass!