![](/img/trans.png)
[英]Why does my python blessings print statement not print in the same spot?
[英]Why does the same statement print two different values?
當我想要理解python自我概念時,我遇到了這個我認為有用的例子。 但是有一部分讓我感到困惑。 為什么print ai
輸出兩個不同的值? 在第一種情況下,輸出為5
,這對我來說很有意義。 但后來幾行同樣的print ai
語句輸出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
在prepare
方法中的以下聲明之前:
self.i = 123
self.i
引用類屬性MyClass.i
(因為未設置實例屬性)
執行self.i = ..
語句后, self.i
引用新值123
。 (這不會影響類屬性MyClass.i
,從而產生新的實例屬性)
您正在prepare()
函數中將類變量i更改為123:
self.i = 123
之后,您通過執行print ai
調用類變量,結果將打印123。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.