Search code examples
pythonoopself

How do I know when to put an argument after self?


Let's consider that you are creating a NFS game. for that we should have a car. Car can have attributes like "color", "company", "speed_limit" etc. and methods like "change_gear", "start", "accelarate", "move" etc. enter image description here

So in this example, why did they put an argument after self for the last function (gear_type after self in the change_gear function), but not the other ones?


Solution

  • Think about an object as an state container. The only way to change its inner state is by calling a method. start, stop and accelerate change the state based on the previous state, they depend on nothing else to work since everything they need is already contained or deducible the the car state. Now, you you want to change a gear you want to change it by something else, by some another gear, so your method need to receive the missing parts.

    Think about method as they were messages, because is about that that OOP is about, sending messages to objects. If you say to a car to start, stop or accelerate the message is complete by itself. Now if you say, change your gear you have to provide a new gear with the message so that the message makes sense band it can change its gear by the one that you provided.

    In Python the first argument of a method is the object it self. This is the state container. This is replaced by the object by the interpreter when you call object.method(arg), becomes object.method(object, arg). You can name it anyway you want but self is a established convention

    I hope this helps