avatar Bite 230. Thumbs up for operator overloading

In this Bite we learn a bit of operator overloading. Finish the Thumbs class that returns an amount of thumbs up (👍) or thumbs down (👎) emojis based on the int it is multiplied with.

Override the corresponding dunder methods to make this work. No constructor method should be needed, the thumbs emojis to be used are defined in constants.

Best to see it in action using the REPL:

>>> from thumbs import Thumbs
>>> th = Thumbs()
>>> th * 1
'👍'
>>> th * 2
'👍👍'
>>> th * 3
'👍👍👍'

Starting 4 it shortens by returns the emoji once, followed by the amount in parentheses:

>>> th * 4
'👍 (4x)'
>>> th * 5
'👍 (5x)'
>>> th * 6
'👍 (6x)'
...

For negative numbers the emoji changes from thumbs up to thumbs down:

>>> th * -1
'👎'
>>> th * -2
'👎👎'
>>> th * -3
'👎👎👎'

Again starting 4 it shows the number in parentheses (this was a real world use case actually):

>>> th * -4
'👎 (4x)'
>>> th * -5
'👎 (5x)'
>>> th * -6
'👎 (6x)'
...

It should raise an exception if the number is 0:

>>> th * 0
Traceback (most recent call last):
...
ValueError: Specify a number

And lastly it should work both ways:

>>> th * 1
'👍'
>>> 1 * th
'👍'
>>> -3 * th
'👎👎👎'
>>> 7 * th
'👍 (7x)'
>>> -6 * th
'👎 (6x)'
>>> 0 * th
...
ValueError: Specify a number

We hope this shows you a bit of the power of operator overloading. If you want to learn more about Python's data model and dunder methods, check out Bob's guest post: Enriching Your Python Classes With Dunder (Magic, Special) Methods.

Have fun and keep calm and code in Python!

Login and get coding
go back Intermediate level
Bitecoin 3X

Will you be Pythonista #99 to crack this Bite?
Resolution time: ~41 min. (avg. submissions of 5-240 min.)
Pythonistas rate this Bite 3.14 on a 1-10 difficulty scale.
» You can do it! 😌

Focus on this Bite hiding sidebars, turn on Focus Mode.

Ask for Help