1

I've researched for hours and have not found a decent explanation of 'self', and it's popping up in every tutorial / python video I watch.. Please explain it as if you were explaining it to an idiot, heres an example code, I do not understand why you would use 'self', what does it do that's useful? I would like to say I know quite a bit of python, but I can't figure out this 'self', explanations appreciated! :)

class className:
    def createName(self, name):
        self.name = name #Whats this 'self' referring to?
    def sayName(self):
        print 'hello %s' % self.name

testing=className()
testing.createName('test')
testing.sayName()
Ewan
  • 14,592
  • 6
  • 48
  • 62
user2993584
  • 139
  • 2
  • 5
  • 13

1 Answers1

1

self is a "cheap" way of introspection/reflection in python. In some ways it's akin to Java's this. So, it's basically a way for an instance of a class to reference its members and attributes.

I'm sure there's a more technical way to explain it, but I've found this to be a good to explain it to people coming from other programming languages.

When I say cheap, I mean it's based on a protocol/convention not on internals. Take the class definition below, for example:

class Friend(object):
    uno = 1
    dos = 2
    def __init__(s):
        s.tres = 3

    def print_it(s):
        print 'Numbers %s, %s, %s' % (s.uno, s.dos, s.tres)

that's a legit class and can be used like any other class in python. so self in itself is not defined or a keyword. It's simply saying, "any instance method will be sent the its own context as the first parameter".

rdodev
  • 3,164
  • 3
  • 26
  • 34