当我试图理解 python self 概念时,我遇到了这个我认为有帮助的例子。但是有一部分让我感到困惑。为什么 print a.i
输出两个不同的值?在第一种情况下,输出是 5
,这对我来说很有意义。但是几行之后,相同的 print a.i
语句输出 123
。
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()
输出
>>> 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
最佳答案
您正在使用同名的全局、局部和实例属性:
def say_hi(): # This is the global function 'say_hi'
return 'hi!'
i = 789 # This is the global 'i'
class MyClass(object):
i = 5 # This is a class attribute 'i'
def prepare(self):
i = 10 # Here, you are creating a new 'i' (local to this function)
self.i = 123 # Here, you are changing the instance attribute 'i'
print i # Here, you are printing the new'ed 'i' (now with value 10)
def say_hi(self): # This is the object method 'say_hi' function
return 'Hi there!'
def say_something(self):
print say_hi() # Here, you are calling the global 'say_hi' function
def say_something_else(self):
print self.say_hi() # Here, you are calling the object method 'say_hi' function
所以输出是正确的:
>>> print say_hi() # global
hi!
>>> print i # global
789
>>> a = MyClass()
>>> a.say_something() # say_something calls the global version
hi!
>>> a.say_something_else() # say_something_else calls the object version
Hi there!
>>> print a.i # class attribute 'i'
5
>>> a.prepare() # prints the local 'i' and change the class attribute 'i'
10
>>> print i # global 'i' is not changed at all
789
>>> print a.i # class attribute 'i' changed to 123 by a.prepare()
123
关于python - 为什么同一条语句打印出两个不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26086359/