Search code examples
pythonooppython-2.7self

Understanding "self" in Python


I saw this example from udacity.com :

def say_hi():
    return 'hi!'

i = 789

class MyClass(object):

    i = 5

    def prepare(self):
        i = 10
        self.i = 123
        print i

    def say_hi(self):
        return 'Hi there!'

    def say_something(self):
        print say_hi()

    def say_something_else(self):
        print self.say_hi()

output:

>>> print say_hi()
hi!
>>> print i
789
>>> a = MyClass()
>>> a.say_something()
hi!
>>> a.say_something_else()
Hi there!
>>> print a.i
5
>>> a.prepare()
10
>>> print i
789
>>> print a.i
123

I understand everything, except why a.say_something() equals hi! and not Hi there!. That is strange for me, because it calls say_something() which is inside the class when it calls say_hi() after that. Guess I missed something important..


Solution

  • Class scopes aren't considered when looking up a name in enclosing scopes. You should always qualify with self. to get a name from the class scope.

    See The scope of names defined in class block doesn't extend to the methods' blocks. Why is that? for a more detailed discussion of this behaviour.