Basic Python OOP

This note is taken from InteractivePython.org website.

Create Class in Python

class Perth:
    def __init__(self, age, city): # __init__ is reserved word for initializing the class. self is required as argument.
        self.age = age
        self.city = city

thisperth = Perth(25, 'Melbourne')

Write any function

def func_name(arg):

or overwrite functions (Operator Overloading)

e.g. overwrite print(thisperth)

class Perth:
    # ....
    
    def __str__(self):
         return self.age

Inheritance: Creating Subclass

Inheritance can be done by using parent class (or Superclass) name like so.

class Perthchild(Perth):

Subclass will get everything from Superclass, and has to call Superclass’s __init__ in its init e.g.

def __init__(self, age, city):
    Perth.__init__(self, age, city)

Beware that in order to create subclass, subclass and superclass should have IS-A Relationship, not HAS-A Relationship (e.g. cat IS animal, and cat house HAS cats)

 

Leave a Reply

Your email address will not be published. Required fields are marked *