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()之后会调用类中的内容.猜猜我错过了一些重要的事情..