create a subclass in python

To create a subclass in Python, you can use the following syntax:

main.py
class ChildClass(ParentClass):
    # ChildClass definition
59 chars
3 lines

Where ParentClass is the name of the class you want to inherit from, and ChildClass is the name of the new subclass you're creating.

Here's an example:

main.py
class Animal:
    def __init__(self, name):
        self.name = name

    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        return "Bark!"
168 chars
11 lines

In the example above, Dog is a subclass of Animal. It inherits the __init__ method, which takes a name parameter, from the Animal class. It also defines its own sound method, which returns a string representing the sound that dogs make.

You can create an instance of the Dog class like this:

main.py
my_dog = Dog("Rufus")
print(my_dog.name)  # outputs "Rufus"
print(my_dog.sound())  # outputs "Bark!"
101 chars
4 lines

gistlibby LogSnag