簡體   English   中英

這個變量聲明如何在python中工作?

[英]How does this variable declaration works in python?

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'..誰能在這里點亮一些光?

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 ,它在內置之前找到。 你也可以使用import __builtin__; __builtin__.type(i) import __builtin__; __builtin__.type(i)在Python 2中import __builtin__; __builtin__.type(i) ,或者import builtins; builtins.type(i) import builtins; builtins.type(i)在Python 3中訪問原始的內置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

請參閱Integer Literals參考文檔

我會很快把答案弄清楚......

i = 0x0800將為i指定十六進制數(0800)的int等效值。

所以,如果我們看起來像是碎片

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM