r/learnpython • u/codehorsey Github codehorsey • Aug 14 '17
I finally understand classes thanks to this presentation.
As a newbie to coding in general and having trouble understanding classes. This helped me a bunch, I hope others can find it useful.
365
Upvotes
53
u/filletrall Aug 14 '17
I want to point out a small (very small) problem with this tutorial:
Here, there's a class attribute named fish, and then there's an instance attribute named fish. The class attribute is never used, because it's being hidden (shadowed) by the instance attribute. You can still get at it:
But it's unneeded, since aquariums in general don't share fish between them. Each instance has fish, independent of any other instance.
It's also confusing for newbies, who might get the idea that all instance attributes needs a shadow class attribute, or that it's a good idea to use class attributes as a sort of "default value". Instead, simply drop the second line:
It's best to only use class attributes to store attributes that describe or otherwise truly belong to the class, and not each instance.
There are definitely cases where putting a list or a dict on the class object makes sense, typically when you wish to track some aggregate property of all the instances, like a sum or a list of the instances. To avoid unintended behavior and make it clear what the intention of the code is, always access class attributes directly on the class object, and not through self: