加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 为什么同一语句打印两个不同的值?

发布时间:2020-12-20 12:07:19 所属栏目:Python 来源:网络整理
导读:当我想要理解 python自我概念时,我遇到了这个我认为有用的例子.但是有一部分让我感到困惑.为什么打印a.i输出两个不同的值?在第一种情况下,输出为5,这对我来说很有意义.但后来几行同样打印a.i语句输出123. def say_hi(): return 'hi!'i = 789class MyClass(o
当我想要理解 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读