I am new to Python so please don’t flame me if I ask something too noobish 🙂
1.
Consider I have a class:
class Test:
def __init__(self, x, y):
self.x = x
self.y = y
def wow():
print 5 * 5
Now I try to create an object of the class:
x = Test(3, 4)
This works as expected. However, when I try to call the method wow(), it returns an error, which is fixed by changing wow() to:
def wow(self)
Why do I need to include self and if I don’t, what does the method mean?
2. In the definition of __init__:
def __init__(self, x, y):
self.x = x
self.y = y
Why do I need to declare x and y, when I can do this:
def __init__(self):
self.x = x
self.y = y
I hope I am being clear…
Thanks for your time.
The instance reference in Python is explicit. That way it can be manipulated by e.g. decorators before finally being passed to the method.
We need to declare
xandyas arguments to the function so that we can use their names within the function, bound to the arguments passed in the corresponding function call.