python – 为什么同一语句打印两个不同的值?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 为什么同一语句打印两个不同的值?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1942字,纯文字阅读大概需要3分钟。
内容图文
![python – 为什么同一语句打印两个不同的值?](/upload/InfoBanner/zyjiaocheng/759/158214aaa5094acaa98906f5e1c4dc87.jpg)
当我想要理解python自我概念时,我遇到了这个我认为有用的例子.但是有一部分让我感到困惑.为什么打印a.i输出两个不同的值?在第一种情况下,输出为5,这对我来说很有意义.但后来几行同样打印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 – 为什么同一语句打印两个不同的值?全部内容,希望文章能够帮你解决python – 为什么同一语句打印两个不同的值?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。