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:



is translated to...

  • A
  • B
  • C
  • D
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.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need