As a new python developer the magic 'self' identifier doesn't make a whole lot of sense. It seems like self is just magically added to the function call
class Foo:
def __init__(self, r):
self.r = r
def a(self, b):
return self.r + b
f = Foo(5)
f.a(2)
7
This should look very normal and if you are a whiz you might say that
f.a(2)
really means that the compiler (interpreter) just adds the instance (f) to the call to give us self. Well you would be right.
But what does that mean?
It means that we can pass any old object into any class. Take the following example
class A:
def __init__(self, r):
self.r = r
def foo(self,x,y):
return self.r+x+y
class B:
def __init__(self, r):
self.r = r
a = A(2)
b = B(2)
print (a.foo(2,4))
print (A.foo(a, 2, 4))
print (A.foo(b, 2, 4))
8 8 8
class Impl:
def foo(self, x, y):
return x + y - self.r
class Data:
def __init__(self, r):
self.r = r
d = Data(5)
Impl.foo(d, 3, 5)
3