Python Classes & Inheritance

Inheritance

class Animal: 
    def \_\_init\_\_(self, name, legs):
        self.name = name
        self.legs = legs

class Dog(Animal):
    def sound(self):
        print("Woof!")

Yoki = Dog("Yoki", 4)
print(Yoki.name) # => YOKI
print(Yoki.legs) # => 4
Yoki.sound()     # => Woof!

Overriding

class ParentClass:
    def print\_self(self):
        print("Parent")

class ChildClass(ParentClass):
    def print\_self(self):
        print("Child")

child_instance = ChildClass()
child_instance.print_self() # => Child

Polymorphism

class ParentClass:
    def print\_self(self):
        print('A')

class ChildClass(ParentClass):
    def print\_self(self):
        print('B')

obj_A = ParentClass()
obj_B = ChildClass()

obj_A.print_self() # => A
obj_B.print_self() # => B

User-defined exceptions

class CustomError(Exception):
    pass

repr() method

class Employee:
    def \_\_init\_\_(self, name):
        self.name = name

    def \_\_repr\_\_(self):
        return self.name

john = Employee('John')
print(john)  # => John

Super() Function

class ParentClass:
    def print\_test(self):
        print("Parent Method")

class ChildClass(ParentClass):
    def print\_test(self):
        print("Child Method")
        # Calls the parent's print\_test()
        super().print_test() 

>>> child_instance = ChildClass()
>>> child_instance.print_test()
Child Method
Parent Method

Class Variables

class MyClass:
    class_variable = "A class variable!"
# => A class variable!
print(MyClass.class_variable)
x = MyClass()

# => A class variable!
print(x.class_variable)

Method

class Dog:
    # Method of the class
    def bark(self):
        print("Ham-Ham")

charlie = Dog()
charlie.bark()   # => "Ham-Ham"

Constructors

class Animal:
    def \_\_init\_\_(self, voice):
        self.voice = voice

cat = Animal('Meow')
print(cat.voice)    # => Meow

dog = Animal('Woof') 
print(dog.voice)    # => Woof
Comments