r/learnpython • 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

17 comments sorted by

53

u/filletrall Aug 14 '17

I want to point out a small (very small) problem with this tutorial:

class Aquarium(object):
    fish = []
    def __init__(self, fish):
        self.fish = fish

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:

>>> Aquarium.fish
[]

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:

class Aquarium(object):
    def __init__(self, fish):
        self.fish = fish

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:

class Payment(object):
    sum = 0
    def __init__(self, amount):
        self.amount = amount
        Payment.sum += amount   # or type(self).sum += amount

1

u/spoiltForChoice Aug 15 '17

if we do not define the fish list, the self.fish assigns itself to fish. What is the difference between self.fish in this snippet:

class Aquarium(object):        
        def __init__(self, fish):
            self.fish = fish

vs the following snippet:

    class Aquarium(object): 
        fish = []
        def __init__(self, fish):
            self.fish = fish

1

u/filletrall Aug 16 '17

The self.fish attribute is the same in both cases. But in the second case there's also a class attribute called fish, Aquarium.fish, that's just an empty list and is not needed or used for anything. :-)

0

u/[deleted] Aug 14 '17

[deleted]

3

u/[deleted] Aug 14 '17

And class attributes can be accessed on instances too:

>>> p1.sum
5

>>> p2.sum
5

But try not to do that unless you have a good reason. It's confusing.

3

u/KubinOnReddit Aug 14 '17

Mostly because this is not really a good name for this. What I find a great usage of class attributes used by instances is game textures loaded by a class and then used by the instance. If you want to, you can change the texture from instance-scope making this approach flexible, while only loading the original texture once.

2

u/TangibleLight Aug 15 '17

Yes, but the problem is that the cases where you'd actually want to do that are few and far between.

If you've got class Payment with a class variable sum that just gets incremented on init, that's not very flexible. What if you have multiple parties making payments? What if you want to double-check that the sum amount is the correct value? What if you want to create a Payment without applying it, maybe to check if a balance is valid?

Usually for things like this, some kind of collection or sequence is better, outside the class:

class Payment:
    def __init__(self, amount):
        self.amount = amount

Then you could have this code in some function, or maybe a method on a different class like Account, which would have payments as an instance attribute.

payments = [
    Payment(100),
    Payment(50),
    Payment(-75),
    Payment(42)
]

balance = sum(p.amount for p in payments)

12

u/Aiognim Aug 14 '17

I really enjoyed the break down and the size of the slides. I could learn a great deal that way.

Props to the author.

Thanks for sharing.

4

u/LeonardFibonacci Aug 14 '17

That was a fantastic presentation! I’m new to python and this cleared a few things up for me. Thank you.

2

u/pookeye Aug 15 '17

this is a great presentation, im still very new to classes, but this helps a lot.

2

u/Thecrawsome Aug 15 '17

I shy away from OOP in-general with Python, personally.

If I need OOP, it's C++. There's a little extra boilerplate, but man, Python is not ideal for OOP. It's too expensive.

2

u/Freezingcow Aug 15 '17

I wish all elements of programming was explained this way. Explaining things with analogy is hands down the best way to teach and learn in my honest opinion. One of my teachers back in the day did this all the time and I've never been more excited than when I went to his classes.

1

u/thisBeAFakeThrowaway Aug 14 '17

I want to get a goldfish now.

1

u/Suruat Aug 14 '17

Awesome!!!

1

u/1giov Aug 15 '17

Awesome slides! Are they available for offline use?

1

u/0k4n3n4s 0kanenas at Github Aug 14 '17

Man that was useful! Thanks for sharing!! ā˜•šŸ•šŸ‘Øā€šŸ’»

0

u/[deleted] Aug 14 '17

[deleted]

2

u/codehorsey Github codehorsey Aug 15 '17

Thanks, I had to share it. Cleared everything up for me :)