# Duck typing philosophy of Python: pass
any object as long as the object contains
the talk() method. The object type is
distinguished at run time.
class Dog:
def bark(self):
print('Barking')
class Duck():
def talk(self):
print('Quack Quack')
class Human():
def talk(self):
print('Speak')
def calltalk(obj):
[Link]()
'''def calltalk(obj):
if hasattr(obj,'talk'):
[Link]()
elif hasattr(obj,'bark'):
[Link]()'''
d=Dog()
[Link]()
du=Duck()
[Link]()
h=Human()
[Link]()
calltalk(du)
calltalk(h)
#calltalk(d)#AttributeError: 'Dog' object
has no attribute 'talk'
# Attribute error can be overcome using
hasattr(object,attribute)that checks
whether object has the attribute or not,
attribute is eother object or method.
'''def calltalk(obj):
if hasattr(obj,'talk'):
[Link]()
elif hasattr(obj,'bark'):
[Link]()'''
# Operator Overloading Ex: '+'
print(10+20)
print("good"+"morning")
# Operator overloading on Rational
objects
# If a method is written such that it can
perform more than one task, it is called
method overloading. Method overloading
which is in C++/Java is not available in
Python. Writing more than one method
with same name is not possible in python.
But, can be achieve by writing method
with several parameters
def sum(a=None, b=None, c=None):
if(a!=None and b!=None and c!=None):
print(a+b+c)
elif a!=None and b!=None:
print(a+b)
else:
print('please enter atleast two
values')
sum(10,20,30)
sum(10,20)
sum(10)
#Method Overriding: When there is a
method in super class, writing the same
method in the sub class so that it replaces
the super class method is called method
overriding. The programmer overrides the
super class method when he doesnot
wants to use them in the sub class.
class Person:
def __init__(self,n,nm):
self.__no=n
[Link]=nm
def write(self):
print(self.__no,[Link])
class Student(Person):
def __init__(self,n,nm,b):
super().__init__(n,nm)
[Link]=b
def write(self):
super().write()
print([Link])
p=Person(10,'kar')
[Link]()
print([Link])
#print(p.__no)#Private
s=Student(5,'kkp','cs')
[Link]()
print([Link])
print([Link])
#print(s.__no)#Private