"If Python doesn't support overloading, how does '+' work which can be either addition or concatenation, correct?" My collegue Peter asked me this once. Let me explain this question, then answer it. And it starts with the word "overloading", which has two different meanings in Python. When you write a class in Python, you can have only one version of each method. For example, this doesn't work: import math class Point: def __init__(self, x, y): self.x, self.y = x, y def distance(self, other_point): # Distance from this point to another point return math.sqrt( (self.x-other_point.x)**2 + (self.y-other_point.y)**2 ) def distance(self, x, y): # Distance from this point to other x-y coords return math.sqrt( (self.x-x)**2 + (self.y-y)**2 ) See the two distance() methods? See how it's defined twice? In Python, only the second version is kept. The first one is silently overwritten and erased. If you call Point.distance() with one argument - matching the first distance(), but not the second - you will get an error. But if you translate this class to Java, the situation is different. Java lets you define both versions of distance(), and Java will use one or the other, depending on how many arguments you pass in. This is called "method overloading". But Python doesn't let you do that. Peter knew this, and that's why he wondered about the "+" operator - and why Python lets you use it for different operations. Doesn't that conflict with Python's "no overloading" rule? The answer is that while Python does not support method overloading... It DOES support operator overloading. And that's why you can use "+" for both strings and numbers, and in fact you can make it work with your own classes as well - using "magic method" hooks. For the "+" operator, we do that by defining a method called __add__. For example, in Point: class Point: def __init__(self, x, y): self.x, self.y = x, y # ... def __add__(self, other): return Point(self.x + other.x, self.y + other.y) This "__add__" method...
First seen: 2026-07-26 09:56
Last seen: 2026-07-26 15:00