PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Easy
Question 28
Python knows what to do when the interpreter spots the + operator between two objects - it looks for the magic method responsible for the called function or operator in order to apply it to the operands (objects). In fact, the following snippet of code:
- var1 = 10
- var2 = 20
- result = var1 + var2
is translated to...
-
A
- var1 = 10
- var2 = 20
- result = var1._add_(var2)
-
B
- var1 = 10
- var2 = 20
- result = var1.add(var2)
-
C
- var1 = 10
- var2 = 20
- result = var1.__add__(var2)
-
D
- var1 = 10
- var2 = 20
- result = var1.__plus__(var2)
Reveal correct answer
Correct answer: C
A.
This is close, but incorrect because the correct method is __add__, not _add_. The underscores are important, as they are part of Python's special method naming convention.
B.
There is no method called add in Python's object model. The correct magic method is __add__.
C.
This is the correct way Python internally handles the + operator. When the + operator is used, Python internally calls the __add__() magic method on the first operand (var1 in this case) and passes the second operand (var2) as an argument.
D.
There is no __plus__ method in Python. The correct method that handles the + operator is __add__.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
