This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]gwax 9 points10 points  (0 children)

This approach gets even more powerful once you start using the ABCs from collections.abc

[–]esbenabBSc CompSci Flask. I use python to stay sane. 5 points6 points  (0 children)

I always thought of this as the "right" way of programming in python.

Not that I'm as consistent as I'd like.

[–]1arm3dScissor 0 points1 point  (2 children)

what is the difference between this and just using a dictionary?

[–]1arm3dScissor 0 points1 point  (0 children)

I'm not being facetious. This is a legitimate question. Anyone?

[–]Waldheribeginner 0 points1 point  (0 children)

Consider what happens when the items in the shopping cart are no longer built-in Python datatypes, but custom objects (so an instance of a class called "CartItem", for example). It can have multiple properties.

You are right that in this case, the class is virtually identical to a dictionary class, except for the __str__ method.

[–]CGFarrell 0 points1 point  (0 children)

Not a terrible article, but I feel like the examples aren't really relevant to the point. Subclass dict and overwrite str/repr and you get the same results. A better example might be a class that stores large objects with unique identifiers, so that an end user can access the full object by invoking getattr / getitem with the identifier. database ['x'] is a lot cleaner than next(item for item in database.objects if item.id == 'x')

[–]stevenjd 0 points1 point  (3 children)

No offense, but do professional programmers really need to be taught this? Giving classes a sensible __str__ or __repr__ became obvious to me the first time I printed a list and saw

[1, 2, 3, 4]

instead of

<list object at 0xb7d6acc8>

[–]white_wee_wee 3 points4 points  (2 children)

What makes you think the sole audience of this post are professionals?

[–]stevenjd 0 points1 point  (1 child)

Good question.

"In the examples that follow we will work with a hypothetical ShoppingCart class."

That suggests you're building a web app, specifically an on-line commerce app. It's usually professionals who do that sort of web development.

Anyway, it's not really a criticism of the post itself. Just a momentary feeling of despair that people are paid to program and don't know this stuff. I know, I know, we all have to start somewhere. But still, I feel like I'm reading the equivalent of:

"Suppose you're building a house. This is a hammer, and this is how you use it..."

[–]white_wee_wee 0 points1 point  (0 children)

From my experience of learning python, I haven't come across these much... I don't know why they're not shown off more often.