Reputation:
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.
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?
Upvotes: 0
Views: 48
Reputation: 6299
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
Upvotes: 0
Reputation: 5774
Simply put you include an argument after self
when your method needs additional information to be executed and that information is located outside the object, else you would be able to access it via self.attribute
Upvotes: 1