Adding a Method
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):
pass
class Hinny(Horse, Donkey):
pass
a1 = Animal()
print(a1.says())
h1 = Horse()
print(h1.says())
d1 = Donkey()
print(d1.says())
m1 = Mule()
print(m1.says())
h1 = Hinny()
print(h1.says())
-
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
@property
def name(self):
return self.hidden_name
@name.setter
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
- Refer Here for the python notebook
Polymorphism
-
Polymorphism is an ability of object to take many forms
-
Look at the following class Diagram
-
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)
print_area(c1)
r1 = Rectangle(length=1, breadth=1)
print_area(r1)
l1 = Lion()
print_area(l1)