Skip to content

Instantly share code, notes, and snippets.

@Kellel
Last active November 10, 2023 01:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kellel/72e2dd6599e488746dd0 to your computer and use it in GitHub Desktop.
Save Kellel/72e2dd6599e488746dd0 to your computer and use it in GitHub Desktop.

Understanding Python Self

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

Normal use of self

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?

Abusing self

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment