類型和運算 (Types and Operations)
Introducing Python Object Types
在非正式的意義上, 在 Python 中, 我們用一些東西做事情.
- "事物" 采取像加法和串聯的形式的操作。
- "東西" 是指我們執行這些操作的對象。
從更正式的角度來看,在 Python 中,資料以對象的形式出現。
As we’ll see, everything is an object in a Python script. Even simple numbers qualify, with values (e.g., 99), and supported operations (addition, subtraction, and so on).
The Python Conceptual Hierarchy (概念上的層級結構)
- Programs are composed of modules. (程式由子產品構成)
- Modules contain statements. (子產品包含語句)
- Statements contain expressions. (語句包含表達式)
- Expressions create and process objects. (表達式建立和處理對象)
Built-in Types (内置類型)

- 在 Python 中沒有類型聲明,運作的表達式的文法決定了建立和使用的對象的類型。
- 一旦建立了一個對象,它就和操作集合綁定了——隻能對一個字元串執行字元串操作,并在清單上進行清單相關操作。
在正式術語中, 這意味着 Python 是動态類型的, 它會自動跟蹤類型, 而不是要求聲明代碼, 但它也是強類型的, 這意味着您可以在僅對象操作上執行對其j進行适合該類型的有效操作。
在 Python 中的每一個對象都可以分為不可變性和可變性。比如數字、字元串、元組是不可變的。不可變的:在建立後不能就地改變。
多态意味着一個操作符 (如
+
) 的意義取決于被操作的對象。這将是 Python 的關鍵思想:不要将代碼限制在特定的類型上,使代碼自動适用于多種類型。
數字類型 (Numeric Types)
In Python, numbers are not really a single object type, but a category of similar types.
完整的 Python 數值類型清單:
英文 | 中文 |
---|---|
Integer and floating-point objects | 整數和浮點數 |
Complex number objects | 複數 |
Decimal: fixed-precision objects | 固定精度的十進制數 |
Fraction: rational number objects | 有理分數 |
Sets: collections with numeric operations | 具有數值運算的集合 |
Booleans: true and false | 布爾類型 |
Built-in functions and modules: , , etc. | 數值相關的内建函數和子產品 |
Expressions; unlimited integer precision; bitwise operations; hex, octal, and binary formats | 表達式; 無窮的整數精度; 按位運算; 16 進制; 8 進制; 2 進制 |
Third-party extensions: vectors, libraries, visualization, plotting, etc. | 第三方擴充 |
Numeric Literals (數值常量)
Integers may be coded in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2), the last three of which are common in some programming domains. Hexadecimals start with a leadingor
0x
, followed by a string of hexadecimal digits (\(0\sim 9\) and \(A\sim F\)). Hex digits may be coded in lower- or uppercase. Octal literals start with a leading
0X
0o
(zero and lower- or uppercase letter
0O
), followed by a string of digits (\(0\sim 7\)). In 2.X, octal literals can also be coded with just a leading , but not in 3.X—this original octal form is too easily confused with decimal, and is replaced by the new
o
format, which can also be used in 2.X as of 2.6. Binary literals, new as of 2.6 and 3.0, begin with a leading
0o
0b
, followed by binary digits (\(0\sim 1\)).
0B
Floor 除法和截斷除法
請注意,在 Python 3.X 中
//
(floor, 向下取整) 運算: 如果是浮點型, 則結果為浮點型;否則, 它是一個整數。下面展示一些 Floor 除法和截斷除法的運算:
20 // 3
6
20. // 3
6.0
from math import floor, trunc
floor(2.5)
2
floor(-2.5)
-3
trunc(2.5)
2
trunc(-2.5)
-2
5 / 2, 5 / -2
(2.5, -2.5)
5 // 2, 5 // -2
(2, -3)
5 / 2., 5 / -2.
(2.5, -2.5)
5 // 2., 5 // -2.
(2.0, -3.0)
trunc(5 / -2)
-2
進制數
0o1, 0o20, 0o377 # 八進制
(1, 16, 255)
0x01, 0x10, 0xFF # 十六進制
(1, 16, 255)
0b1, 0b10000, 0b11111111 # 二進制
(1, 16, 255)
oct(64), hex(64), bin(64)
('0o100', '0x40', '0b1000000')
int
會将一個數字的字元串變換為一個整數,并且通過第二個參數來确定變換後的數字進制:
int('64'), int('100', 8), int('40', 16), int('1000000', 2)
(64, 64, 64, 64)
int('0x40', 16), int('0b1000000', 2)
(64, 64)
eval('64'), eval('0o100'), eval('0x40'), eval('0b1000000')
(64, 64, 64, 64)
'{0:0}, {1:x}, {2:b}'.format(64, 64, 64)
'64, 40, 1000000'
'%o, %x, %X' % (64, 255, 255)
'100, ff, FF'
位操作
x = 1
x << 2 # Shift left 2 bits
4
x | 2 # Bitwise OR
3
x & 1 # Bitwise AND
1
X = 99
bin(X), X.bit_length() # `X.bit_length()` 獲得二進制字元串的長度
('0b1100011', 7)
round(1/3, 7)
0.3333333
使用分數和小數可以避免精度的損失!
小數
from decimal import Decimal, getcontext
Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
Decimal.from_float(1.25)
Decimal('1.25')
設定全局精度
Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')
getcontext().prec
28
getcontext().prec = 4 # 改變全局精度
Decimal(1) / Decimal(7)
Decimal('0.1429')
分數
from fractions import Fraction
x = Fraction(1, 3)
x
Fraction(1, 3)
y = Fraction(4, 6)
y
Fraction(2, 3)
x + y
Fraction(1, 1)
x - y
Fraction(-1, 3)
x * y
Fraction(2, 9)
Fraction('.25')
Fraction(1, 4)
Fraction('1.25')
Fraction(5, 4)
Fraction('.25') + Fraction('1.25')
Fraction(3, 2)
分數還有一個
from_float
方法,并且接受一個
Fraction
作為參數。
(2.5).as_integer_ratio()
(5, 2)
f = 2.5
z = Fraction(*f.as_integer_ratio())
z
Fraction(5, 2)
x
Fraction(1, 3)
float(x)
0.3333333333333333
Fraction.from_float(1.75)
Fraction(7, 4)
a = x + Fraction(*(4.0/3).as_integer_ratio())
a
Fraction(22517998136852479, 13510798882111488)
a.limit_denominator(10) # 取近似
Fraction(5, 3)
集合
集合本質上具有基本的數學特性,與數學中的集合的概念十分吻合!
有兩種建立方式:
set()
和
{1, 'f'}
注意,空集合隻能使用
set()
建立,因為
{}
表示空字典。
a = set([1, 3, 4])
a
{1, 3, 4}
b = {1, 3 ,4}
b
{1, 3, 4}
print(type(a))
print(type(b))
<class 'set'>
<class 'set'>
set('spam')
{'a', 'm', 'p', 's'}
{(2, 3), (2, 4), (2, 3)}
{(2, 3), (2, 4)}
詳細内容見 python——序列 & 集合 & 映射.
集合隻能包含不可變的 (即可散列的) 對象類型。
{[3, 4], 6}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-15-870a26241930> in <module>()
----> 1 {[3, 4], 6}
TypeError: unhashable type: 'list'
集合解析
{x*4 for x in 'spam'}
{'aaaa', 'mmmm', 'pppp', 'ssss'}
集合的作用
set()
具有元素的去重功能。
動态類型簡介
在 Python 中,類型是在運作過程中自動決定的,而不是通過代碼聲明。這意味着沒有必要事先聲明變量 (隻要記住,這個概念實質上對變量、對象和它們之間的關系都适用)。
- 變量建立:一個變量(也就是變量名),就像
, 當代碼第一次給它指派時就建立了它。之後的指派将會改變已經建立的變量名的值。從技術上講,python 在代碼運作之前先檢測變量名,可以當成是最初的指派建立變量。a
- 變量類型:變量永遠不會有任何的和它關聯的類型資訊或限制。類型的概念是存在于對象中而不是變量名中。變量原本是通用的,它隻是一個特定的時間點,簡單地引用了一個特定的對象而已。
- 變量使用:當變量出現在表達式中,它會馬上被目前所引用的對象所代替,無論這個對象是什麼類型。此外,所有的變量必須在其使用前明确的指派,使用未指派的變量會産生錯誤。
總而言之,變量在指派的時候才建立,它可以引用任何類型的對象,并且必須在引用之前指派。
變量
- Variables are created when they are first assigned values.
- Variables are replaced with their values when used in expressions.
- Variables must be assigned before they can be used in expressions.
- Variables refer to objects and are never declared ahead of time.
在内部,變量事實上是到對象内容空間的一個指針。在 Python 中從變量到對象的連接配接稱為引用。也就是說,引用是一種關系,以記憶體中的指針的形式實作。一旦變量被使用 (也就是說被引用),Python 自動跟随這個變量到對象的連接配接。
- 變量是一個系統表的元素,擁有指向對象的連接配接的空間。
- 對象是配置設定的一塊記憶體,有足夠的空間去表示它們所代表的值。
- 引用是自動形成的從變量到對象的指針。
- 類型标志符:辨別對象類型;
- 引用計數器:用來決定是不是可以回收對象。
對象的垃圾收集
探尋有趣之事!