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 trialEric Peppler
3,675 PointsSo confused
I've been doing this for awhile now and this is the most confused I've been yet...what is the point of what he's doing? I've watched the video 3 times and I still have no clue what I'm even watching. Instead of age = 25, age+5=30...he's defining a class and within the class he's defining a method that adds? Then he's creating a NumString instance, which ends up as an int or float...and adding it to an int? What am I supposed to be taking away from this lesson?
1 Answer
Chris Freeman
Treehouse Moderator 68,457 PointsThe takeaway is not obvious. It's probably "if you create a class that you wish to use math on its instances, you'll need to create these math handling methods". This specific example of a string that can be operated upon with addition is as basic one can make. The idea being to show a simple non-math object that can be added.
Normal strings can be also added together, but only to other strings. Their __add__
results in a new string through concatenation. Strings can be multiplied, but the __mul__
method raises an error if the "other" is a non-int
.
Another example, imagine a Bookshelf
class, where the __add__
method added all the books from another Bookshelf
class to its own inventory.
Some __add__
methods add steps to do type checking and only allow adding to same type objects.
Post back if you need more help. Good Luck!
Eric Peppler
3,675 PointsEric Peppler
3,675 PointsAha, I think I'm understanding better now.
"Another example, imagine a Bookshelf class, where the
__add__
method added all the books from another Bookshelf class to its own inventory."So if I defined the bookshelf class method
__add__
to add their inventories together, I could something like book_shelf1 + book_shelf2 and I would receive a third bookshelf instance (or perhaps the first again, the way you phrased it) with both inventories now merged? Whereas, before, the interpreter would have no idea what the addition symbol was supposed to do there, correct?[MOD: added backtick (`) to escape underscores -cf]
Chris Freeman
Treehouse Moderator 68,457 PointsChris Freeman
Treehouse Moderator 68,457 PointsExactly.
Alternatively:
Eric Peppler
3,675 PointsEric Peppler
3,675 PointsNiice, got it. Appreciate the help!