【问题标题】:Why do the objects __name__ and __main__ have different identities in Python? [duplicate]为什么对象 __name__ 和 __main__ 在 Python 中有不同的标识? [复制]
【发布时间】:2014-08-16 00:03:49
【问题描述】:

我很好奇为什么用is 替换== 会导致.py 在直接启动时失败。

if __name__ == '__main__':
    main()

对

if __name__ is '__main__':
    main()

对象标识在这里如何工作?

我特别好奇 __name__ 和 __main__ 具有不同身份的机制和目的。

【问题讨论】:

  • 我很好奇为什么 name 和 main 具有不同身份的机制,而不是对象身份的一般概念。

标签: python main identity


【解决方案1】:

is 表示这两个东西是同一个对象(即它们具有相同的id)。显然__name__ 与'__main__' 是不同的字符串(即使它们具有相同的文本)。

一般来说,只有在您真正的意思是“检查这些是完全相同对象”时才使用is——切勿使用它来表示“这些对象相等”。

【讨论】:

  • 获取不“完全相同”的字符串的一种方法是拆分列表。例如'one __main__ two'.split()[1] is '__main__' 返回False。 is 对 sys.argv 中的字符串不是一个好的测试。
【解决方案2】:

几个例子会让它更明显:

In [7]: foo = 1000

In [8]: bar = 1000

In [9]: foo is bar # same value but different objects so identity test is False
Out[9]: False

In [10]: foo == bar # equality test is True
Out[10]: True

In [11]: id(foo) # both have different id's
Out[11]: 41007616

In [12]: id(bar)
Out[12]: 40841432

In [13]: foo = bar # now make foo point to the object bar

In [14]: foo is bar # now foo is bar so identity check is True
Out[14]: True

In [15]: id(bar) # matching id's
Out[15]: 40841432

In [16]: id(foo)
Out[16]: 40841432

要比较值,请使用== 来检查身份,请使用is

需要注意的是小整数 -5 到 256 和字符串在 python 中被缓存和重用,所以如果你分配 a = 10 和 b = 10,它们实际上都指向同一个对象,所以 @987654328 @ .

In [20]: a = 256    
In [21]: b = 256
In [22]: a is b
Out[22]: True
In [23]: a = 257
In [24]: b = 257    
In [25]: a is b
Out[25]: False
In [26]: foo = "foo"
In [27]: bar = "foo"   
In [28]: foo is bar
Out[28]: True
In [29]: foo = "$bar"
In [30]: bar = "$bar"
In [31]: foo is bar # now False because it does not start with an _ or a letter
Out[31]: False

只有以underscore 或letter 开头并且仅包含letters、numbers 或underscores 的字符串才会被缓存:

__main__ 失败的最后一个例子:

# first  __main__  object inside locals dict, second is just a string __main__
print id(locals()['__name__']),id("__main__")  
print (locals()['__name__']) is "__main__" # so not the same object 
print (locals()['__name__'])  == "__main__" # but == strings

if __name__ == "__main__":
    print id(locals()['__name__']), id(__name__ ) # same id's 
    print (locals()['__name__']) is __name__ ) # same object stored in locals

140168071262544 140168071262592
False
True
140168071262544 140168071262544
True

【讨论】:

  • 但是,为了混淆,试试foo = 100 和bar = 100。对于 cPython,foo is bar => True 因为 Python 对缓存和重用小整数对象进行了优化。使用is 时要非常小心的另一个原因。
  • @NedDeily,我知道有人会说我要添加它,但我认为它只会让事情变得更加混乱,bar = "foo" 和 foo = "foo" 也会让事情变得混乱。
猜你喜欢
  • 2010-12-29
  • 2013-09-01
  • 2017-05-19
  • 2018-11-22
相关资源
最近更新 更多