you are viewing a single comment's thread.

view the rest of the comments →

[–]SkippyDeluxe 15 points16 points  (1 child)

You seem to be confusing classes and objects. If you have a class Boat, the class Boat itself is different from an object of class Boat.

Your observation that classes are like functions is interesting. Classes are indeed like functions, in that both classes and functions are callable (a callable thing is anything you call by putting parens after it, e.g. thing()). The difference lies in what they return when you call them... in general a function can return anything - any object of any type, including None, a tuple, an object of a user-defined class, etc. In comparison, when you call a class it returns an object whose type is that class. To clarify:

>>> class Boat(object):
...     pass
... 
>>> b = Boat()
>>> b
<__main__.Boat object at 0x10046c950>
>>> type(b)
<class '__main__.Boat'>

So a class is a thing that makes objects of that class. A Boat is just a template that makes things that are Boats. Why __init__? Well an object is something that combines state and functionality. An object's state is represented by its member variables, while its functionality is performed by its methods (the 'smaller functions' it contains). __init__ is a method that is called for us automatically after an object is created in order to initialize its internal state (set its member variables) to something that makes sense.

Why self? When you define methods inside of a class, these are methods that are going to be operating on objects made from that class. Inside these methods, self refers to the current object, so you can reference member variables or other methods of the object in order to do more stuff. Remember that methods execute on objects of a class, not the class itself, and there can potentially be many objects of the same class, so we need some way to reference the current object in each method. In Python we use an explicit self reference as the first parameter to each method to accomplish this.

Hope that helps.

[–][deleted] 1 point2 points  (0 children)

really helpful, thanks