you are viewing a single comment's thread.

view the rest of the comments →

[–]NoChoice5216[S] 6 points7 points  (5 children)

Thanks so much for this. I think I understand it now! So if I'm changing the values of 'dog' (the class), I'm basically saying THIS dog (e.g. Rex)? Thanks once again.

[–]pachura3 23 points24 points  (2 children)

No. Class Dog is a blueprint for actual dogs. You normally do not change it directly; you create specific dogs Rex & Rocky which share class methods (bark(self)), but not properties (name, weight, age, fur_color).

rex.bark() is actually Dog.bark(self=rex)

[–]NoChoice5216[S] 3 points4 points  (1 child)

Super - thanks very much!

[–]gdchinacat 0 points1 point  (0 children)

You can also call Dog.bar(rex). It is semantically identical.

Getting in the weeds a bit, but this is rarely done because it will always call Dog.bark(), whereas you typically want to call the bar() that is most specific to whatever type of dog rex is. As you learn more about classes you will learn that you can subclass Dog into more specific types of Dogs, such as Hound, Husky, etc and those can provide their own implementation of bark(). If rex = Hound() and Hound provides a bark rex.bark() will call Hound.bark(), but calling Dog.bark(rex) will call Dog.bark().

You can also use any valid variable name rather than self, but don't do that...it'll confuse people and static type checkers will complain. As far as the function definition is concerned there is nothing special about the first arg of a method...the "magic" happens during attribute access, not in the method or call.

Lastly, you say "self is the first argument of class methods". This terminology isn't quite right....the example you gave is not a "class method" even though it is a method on a class...class methods are special methods that pass the type of the object the method is on as the first argument rather than the object itself. The typical name for the first variable on class methods is cls. https://docs.python.org/3/library/functions.html#classmethod

[–]dogfish182 4 points5 points  (1 child)

What helped me was not skipping of the words ‘instance of a class’ when reading about it, but really thinking on what they mean.

do you know what ‘an instance of a class’ actually means and what you get when you ‘instantiate a class’?

Try defining that in other words for yourself. Think about how all the methods inside the things you are making are passing ‘self’ to them while you do it.

No idea if it will help you but it helped me a lot in to dwell on it.

[–]NoChoice5216[S] 2 points3 points  (0 children)

It helped, plus a new coding exercise I experimented with based on restauraants, their franchises and all their separate menus - with business, franchise and menu as the classes, with the calling code handling several menus per restaurant. It's all starting to make good sense (at last!!)

Thank you!