这个变量声明在Python中是如何工作的?

3
i = 0x0800

我理解这里的意思是0x0800是一个十六进制数,其中'0x'表示十六进制类型,后面的数字'0800'是一个2字节的十六进制数。当将其赋值给变量'i'时,检查其类型时出现了错误。

>>> type(i)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

这里我理解为'i'应该是一个int对象。当我尝试下面的代码时,我更加困惑了:

>>> print i
2048

“2048”是一款数字游戏,玩家需要通过滑动方块来合并相同数字的方块,最终得到一个2048的方块。这款游戏在移动端非常流行。

7
你给type赋了一个值,它不是内置函数。 - Martijn Pieters
关于i = 0x0800如何工作,请参见https://docs.python.org/2/reference/lexical_analysis.html#integer-and-long-integer-literals。 - jonrsharpe
2个回答

9

i 是一个整数,但是你重新定义了type

>>> i = 0x0800
>>> i
2048
>>> type(i)
<type 'int'>
>>> type = 42
>>> type(i)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del type
>>> type(i)
<type 'int'>

请注意type = 42这一行;我创建了一个名为type的新全局变量,它优先于内置变量。你也可以在Python2中使用import __builtin__; __builtin__.type(i),或者在Python3中使用import builtins; builtins.type(i)来访问原始的内置type()函数。
>>> import __builtin__
>>> type = 42
>>> __builtin__.type(type)
<type 'int'>
>>> type(type)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del type
>>> type(type)
<type 'type'>

0x 表示法只是指定整型字面量的几种方式之一。在这里,你仍然是生成一个常规整数,只是定义值的语法不同而已。以下所有表示法都产生相同的整数值:

0x0800          # hexadecimal
0o04000         # octal, Python 2 also accepts 0400
0b100000000000  # binary
2048            # decimal

请查看整数字面值参考文档


我的错..明白了...点赞 - harveyD

0

我会快速给出我找到的答案...

i = 0x0800 将把十六进制数(0800)的整数等价值赋给 i。

因此,如果我们将其分解,它看起来像:

 >>> i
 2048
 >>> 
 >>> (pow(16,3) * 0) + ( pow(16,2) * 8 ) + (pow (16,1) * 0 ) + (pow(16,0) * 0)
 2048

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接