Python Classroom Series – 22/Jun/2021

Adding a Method

Refer Here

Multiple Inheritance

  • Sample
class Animal:
    def says(self):
        return 'I speak!'

class Horse(Animal):
    def says(self):
        return 'Neigh............'

class Donkey(Animal):
    def says(self):
        return 'Hee-haw.............'

class Mule(Donkey, Horse):

class Hinny(Horse, Donkey):

a1 = Animal()

h1 = Horse()

d1 = Donkey()

m1 = Mule()

h1 = Hinny()
  • If we look for the method or attribute of Mule, Python will look at the following things in the order

    • The object itself of type Mule
    • The object’s class (Mule)
    • The class’s first parent (Donkey)
    • The class’s second parent (Horse)
    • The grand parent class.
  • Python has a special magical attribute __mro__ which will display the method resolution order for a class

  • Refer Here for the example used

Attribute Access

  • In Python, object attributes and methods are normally public and you are expected to behave yourself (this is called as ‘consenting adults’ policy’ )
class Dog:
    def __init__(self, dog_name):
        self.hidden_name = dog_name

    def name(self):
        return self.hidden_name
    def name(self, dog_name):
        self.hidden_name = dog_name
  • Name Mangling for privacy: Python has a naming convention for attributes that should not be visible outside of class definition, begin with two underscores (__)
  • We need to replace hidden_name with __name
  • In python we use the following conventions for attributes
__<attribute name>  ==> Private 
_<attribute> ==> Protected


  • Polymorphism is an ability of object to take many forms

  • Look at the following class Diagram Preview

  • Sample code

circle = Circle()
triangle = Triangle()

def print_area(shape):
    print(f"Area is {shape.area()}")

Duck Typing

  • Python is a dynamic languages.
  • Duck typing is from the phrase
if it looks like duck and quacks like duck its a duck
  • Example

class Shape():
    def area(self):
        return 0

class Rectangle(Shape):
    def __init__(self, length, breadth):
        self.__length = length
        self.__breadth = breadth

    def area(self):
        return self.__breadth * self.__length

class Circle(Shape):
    def __init__(self, radius):
        self.__radius = radius

    def area(self):
        import math
        return math.pi * (self.__radius ** 2)

class Lion:
    def area(self):
        return "jungle"

def print_area(shape):
    print(f"area is {shape.area()}")

c1 = Circle(radius=1)

r1 = Rectangle(length=1, breadth=1)

l1 = Lion()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin