理解Python中的"自我"

Dan*_*iel 0 python oop self python-2.7

我在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()
Run Code Online (Sandbox Code Playgroud)

输出:

>>> 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
Run Code Online (Sandbox Code Playgroud)

我理解一切,除了为什么a.say_something()等于hi!和不等Hi there!.这对我来说很奇怪,因为它say_something()在调用say_hi()之后会调用类中的内容.猜猜我错过了一些重要的事情..

Sve*_*ach 5

在封闭范围中查找名称时,不考虑类范围.您应该始终有资格self.从类范围中获取名称.

请参见类块中定义的名称范围不会扩展到方法的块.这是为什么?有关此行为的更详细讨论.