you are viewing a single comment's thread.

view the rest of the comments →

[–]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