does a python object need to be given the same number of arguments as its class?
So I came across this class definition in a pygame tutorial:
class GameObject:
def _init_(self,image,height,speed):
self.speed = speed
self.image = image
self.pos = image.get_squarerect().move(0,height)
def move(self):
self.pos = self.pos.move(0, self.speed)
if self.pos.right > 600:
self.pos.left = 0
The coder then does this to fill an array(?) with objects:
objects = []
for x in range(10):
o=GameObject(player, x*40, x)
objects.append(o)
My question is why is it that only 3 arguments 开发者_开发技巧are passed when instantiating the object, but the class was made to accept 4 of them?
self
is passed implicitly, it's a reference to the current instantiation of the object. This is discussed in the official tutorial here: http://docs.python.org/release/2.7/tutorial/classes.html#random-remarks
The self object is supplied implicitly on every method call.
For __init__
, it's a brand new object and Python supplies a reference to that brand new object as self.
For method calls other than __init__
, you actually supply the object which is referenced by self, not as an explicit argument but in the object on which you call the method (object.method(foo) corresponds to, inside the definition of object's class, "def method(self, foo)").
So in your example, __init__
takes 4 arguments (including self) but is called with only 3 (excluding self). The "move" method takes 1 argument (self) but would be called with 0 arguments.
Python requires that the first argument to any instance method be whatever name you choose to refer to the current instance.
Using the name 'self' is a convention that should, imo, be strictly adhered to, but it is just a convention.
In case you never came across a language that used 'self' or 'this', here's a quick rundown of what's going on:
Defining a class means you're writing code inside a box (a 'namespace' really) for later use. "Later use" basically means you'll instantiate the class, thereby creating an object. While you might well instantiate your object by doing "myobj = myClass", thereby making the name of your object "myobj", there's no way to know what its name will be at the time you actually write the code for the class. That's why you use 'self'.
精彩评论