In an example like this:
def class MyClass:
def __init__():
self.attribute = None
def my_method(self, some_parameter):
self.attribute = some_parameter
attribute
is defined as an attribute (or instance variable) on MyClass
. This means that every instance of MyClass
(a MyClass
object) will have its own copy of attribute
.
Since every normal method (a function defined on the class) expects the first argument to be the object itself (which you don't have to pass; Python will pass it automatically), you can use self
to refer to the instance the method was called on. (I say 'normal', because there are also 'static' and 'class' methods, but forget about those for now.)
So, in this example:
an_object = MyClass()
an_object.my_method(10)
print(an_object.attribute)
This works, because in the body of .my_method
, the passed value, which gets assigned to some_parameter
is assigned to the attribute
attribute of an_object
, because an_object
is assigned to self
in that call. Mind you, self
could have been called anything; naming the first parameter self
is just a convention you should follow.
The reason some_parameter
does not need self.
is because it is just another parameter of a function. It's not an attribute of self
— of the object the method was called on.
So, when compared to your code, you should say: steps
does not need self.
because it is not an attribute of a Player
instance. It is just a parameter of a method defined on Player
, and the value is accessible like any parameter is in a function body. The instance of a Player
object is passed as self
, and you can change its attributes by accessing them on self
inside the function body.
A clue why you didn't grasp this is that you call position
an 'argument', but an argument is something passed to a function, to a specific parameter; and a parameter is an internal variable of a function that is assigned the argument. position
is an attribute of an object.
So, when calling player.move(2)
, 2
is the argument, steps
is the parameter in the body of move()
and position
is the attribute of player
, with player
being the Player
class instance (or 'object') accessible through the self
parameter in the body of move()
.