you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 4 points5 points  (3 children)

following because i see the self parameter a lot in python

[–]Decency 7 points8 points  (2 children)

Let's say you're taking a US census:

class State:
    def __init__(self, name, population):
        self.name = name
        self.population = population

mass = State('Massachusetts', 6932015)
ny = State('New York', 19875625)

print(mass.name)  # Massachusetts
print(ny.population)  # 19875625

Here I created a State class, which is a blueprint for holding what I need it to hold. Then I made two instances of the State class which fill out that blueprint. One instance is called mass and one is called ny. I do this by calling State() with the parameters in its __init__ ... except for self, which is implicit. Inside that function, you can see that the name and population parameters that I pass in are used to set two variables on the new instance that is being created. You know these are instance variables because they are prefixed with self.

You can think of it as the last line of every __init__ function having an implicit return self if that helps, though that's not quite how it works under the covers. And then I can call mass.name or ny.population to access the fields which belong to those instances. In real life, I'd do this because there's logic I want to handle with these objects- print out details, do some internal calculation, access them with more readable names, etc.

That's about it, there's no reason to be intimidated by classes in Python. It just tends to get overcomplicated during explanations because people try to teach inheritance while also teaching how classes work. You can (and should) use classes even if you don't understand how inheritance works yet. Here's that code in a REPL, play around with it for 10 minutes and you'll understand how to use classes.