Lecture 16
Lecture 16
• 2+3
• 5*7
• “Hello”*7
Operator Overloading
• d = Duck()
• e = Duck()
• d+e ????
Operator Overloading
• d = Duck()
• e = Duck()
• d+e ????
• Time to make it happen
Operator Overloading
• Operator overloading is a process of making your native operators
work for objects they’re not defined for
Why only
duck?
Operator Overloading
class Duck:
def __init__(self):
print("Duck created")
def print(self):
print("I'm a duck")
Operator Overloading
class Swan:
def __init__(self):
print("Swan created")
def print(self):
print("I'm a Swan")
Operator Overloading
class Duck:
def __init__(self):
print("Duck created")
def print(self):
print("I'm a duck")
def __add__(self, other):
if isinstance(other, Duck):
return Swan()
Operator Overloading
d = Duck()
e = Duck()
f = d+e
d.print()
e.print()
f.print()
Operator Overloading
d = Duck()
e = Duck()
f = d+e
d.print()
e.print()
f.print()
Super
Cool!
Operator Overloading
class Duck:
def __init__(self):
print("Duck created")
def print(self):
print("I'm a duck")
def __add__(self, other):
if isinstance(other, Duck):
return Swan()
else: ?
Which operators are supported?
+ __add__(self, other)
– __sub__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
// __floordiv__(self, other)
% __mod__(self, other)
** __pow__(self, other)
>> __rshift__(self, other)
<< __lshift__(self, other)
& __and__(self, other)
| __or__(self, other)
^ __xor__(self, other)
Which operators are supported?
x = d+e+f+g