【问题标题】:How does this variable declaration works in python?这个变量声明在 python 中是如何工作的?
【发布时间】:2015-10-29 17:42:23
【问题描述】:
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”.. 有人可以在这里说明一下吗?

【问题讨论】:

标签: python python-2.7 hex


【解决方案1】:

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,它是在内置之前找到的。您还可以在 Python 2 中使用 import __builtin__; __builtin__.type(i),或在 Python 3 中使用 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 表示法只是指定整数文字的几种方法之一。您仍在生成常规整数,只有 syntax 用于定义值的方式在此处有所不同。以下所有符号都产生完全相同的整数值:

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

请参阅Integer Literals reference documentation

【讨论】:

  • 我的错……知道了……竖起大拇指
【解决方案2】:

我会很快把我想出的答案....

i = 0x0800 将为 i 分配一个等效于十六进制数 (0800) 的 int。

所以如果我们分解成碎片,这看起来像

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 2018-05-01
    • 2015-02-05
    • 1970-01-01
    • 2011-05-24
    • 2015-08-07
    • 1970-01-01
    相关资源
    最近更新 更多