redefine new in python code example
Example 1: overloading methods python
class A():
def __init__(self, name):
self.name = name
def __add__(self, b):
return (str(self.name) + " " + str(b.name))
def __str__(self):
return self.name
Var1 = A('Gabriel')
Var2 = A('Stone')
Var3 = Var1 + Var2
print(Var1)
print(Var2)
print(Var3)
Example 2: python operator overloading deal with type
def __add__(self, other):
if isinstance(other, self.__class__):
return self.x + other.x
elif isinstance(other, int):
return self.x + other
else:
raise TypeError("unsupported operand type(s) for +: '{}' and '{}'").format(self.__class__, type(other))