Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python Dice Roller Comparing and Combining Dice

Joseph Raker
Joseph Raker
Courses Plus Student 3,354 Points

Comparing and Combining Dice questions

I am working through the Comparing and Combining Dice video and have a couple of questions.

1 - In the ge and le commands, why do we need to use the separate "or" operator for determining the relative value of int(self). Why not just use "return int(self) >= other"?

2 - I understand the reason for needing radd. My question is, if radd first checks (other).add(self) and, if it throws and error, it checks the reverse, why do we need to input the add at all? It seems to me that radd would cover every instance.

Thank you and I look forward to the comments.

2 Answers

Alex Koumparos
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Joseph.

1: In the teacher's notes, Kenneth anticipated your question and wrote:

Before you ask

Yes, I could have done something like:

def __le__(self, other):
     return int(self) <= other

Either format (long or short) is fine and produces the same result.

2: radd is used whenever the object is 'being added' rather than the object 'doing the adding'. In typical situations, addition is commutative (a + b == b + a) and so there doesn't need to be separate behaviour for handling addition depending on whether the object in question is on the left or the right. In the particular case here, the type knows that addition is commutative so the radd function can just reverse the operands and use the already-implemented add function.

However, we are able to overload addition and implement anything we like, even if it doesn't exactly look like traditional arithmetic. One example is string concatenation, which overloads the add operator to provide a convenient way of joining strings. In this case, of course, "hello " + "world" is certainly NOT the same as "world" + "hello " and as such the radd method for strings needs to be a bit cleverer than just reversing the operands and using add.

Hope that's clear