

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 6
click for more info
Not enough gems
Cost: 6 gems
1: Polymorphism
incomplete
2: Get Edges
incomplete
3: Overlap
incomplete
4: Dragon Area
incomplete
5: Polymorphism Review
incomplete
6: Operator Overloading
incomplete
7: Operator Overload Review
incomplete
8: Overriding Built-in Methods
incomplete
9: Polymorphism Practice
incomplete
10: Polymorphism Practice
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Another kind of built-in polymorphism in Python is the ability to override how an operator works. For example, the + operator works for built-in types like integers and strings.
print(3 + 4)
# 7
print("three " + "four")
# three four
Custom classes on the other hand don't have any built-in support for those operators:
class Point:
def __init__(self, x: int, y: int) -> None:
self.x = x
self.y = y
p1 = Point(4, 5)
p2 = Point(2, 3)
p3 = p1 + p2
# TypeError: unsupported operand type(s) for +: 'Point' and 'Point'
But we can add our own support! Python uses special methods with double underscores, sometimes called "dunder methods", to hook into built-in behaviors. You've already used __init__ to customize how objects are created. If we create an __add__(self, other) method on our class, the Python interpreter will use it when instances of the class are being added with the + operator. The name of the second parameter (other in this example) is just a convention - you can use any valid parameter name. Here's an example:
class Point:
def __init__(self, x: int, y: int) -> None:
self.x = x
self.y = y
def __add__(self, other: "Point") -> "Point":
x = self.x + other.x
y = self.y + other.y
return Point(x, y)
p1 = Point(4, 5)
p2 = Point(2, 3)
p3 = p1 + p2
# p3 is (6, 8)
Now, when p1 + p2 is executed, under the hood the Python interpreter just calls p1.__add__(p2).
In Age of Dragons, players craft new weapons from old ones. To keep this mechanic simple for other developers, we'll use operator overloading on the Sword class.
Observe how the test suite uses the + operator to craft the swords.
Create an __add__(self, other: "Sword") -> "Sword" method on the Sword class.
Note that a sword's sword_type is just a string, one of:
bronzeironsteel