Python 3.1 快速導覽 - 變數與物件

Python 中所有東西都是物件 (object) ,這是說 Python 裡的資料 (data) 都是物件。凡是物件都有 id 號碼、型態 (type) 及數值 (value) ,分別可用以下三個內建函數取得

  • id()
  • type()
  • print()


id() 取得物件的 id 號碼,其為整數值, type() ,得到 'type' 類別的物件, print() 印出物件的數值,或是印出物件的字串 (string) 表達形式,並無回傳值 (return value) 。


變數 (variable) 為 Python 中自行定義的識別字 (identifier) ,若將物件的字面常數 (literal) 或定義形式指派給變數,該變數便具有物件的控制權。


以下程式建立變數 a 然後以 print() 印出 type() 回傳 'type' 類別物件的字串形式
a = 33
print(type(id(a)))
print(type(type(a)))
print(type(print(a)))

a = "33"
print(type(id(a)))
print(type(type(a)))
print(type(print(a)))


# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:obj1.py
# 功能:示範 Python 程式 
# 作者:張凱慶
# 時間:西元 2010 年 12 月 */


執行結果如下



第 3 行及第 8 行
print(type(print(a)))


這裡會先印出變數 a 的值,然後取得 type(print(a)) 回傳的 None ,所以會得到 'NoneType' 。


物件的值可以是可變的 (mutable) ,或是不可變的 (immutable) ,通常這是說複合資料型態 (compound data type) 的元素 (element) 是否可以替換,例如序對 (tuple) 及字串是不可變的,而串列 (list) 或字典 (dictionary) 是可變的。


當物件不再使用時,直譯器會自動垃圾收集 (garbage collection) ,釋放記憶體空間。例如上例中,當變數 a 重新指派給 另一個字串物件 "33" 時,原本的整數物件 33 便會被直譯器清除掉。


物件有屬性 (attribute) 及方法 (method) ,透過變數運用小數點符號 . 就能存取該物件的屬性、方法。許多 built-ins 的物件已具有預先定義的屬性或方法,以下程式示範不同物件的內建方法
a = 0.0
print(a.__str__())
print(a.__bool__())

a = 33
print(a.__str__())
print(a.__bool__())

a = "33"
print(a.__str__())
print(a.__len__())

# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:obj2.py
# 功能:示範 Python 程式 
# 作者:張凱慶
# 時間:西元 2010 年 12 月 */


執行結果如下



許多預先定義的方法或屬性,識別名稱前後都用連續兩個底線符號 _ ,如下
__method__()


上面例子的 __str__() 回傳物件的字串形式, __bool__() 回傳物件的真假值, __len__() 回傳複合資料型態物件的長度,也就是所具有元素的總數。


屬性類似變數,不過是物件專有的,方法類似函數 (function) ,也是物件專有的,不同的 built-ins 依物件特性會有不同預先定義的屬性或方法。各種 built-ins 預先定義的屬性或方法,詳細需查 The Python Standard Library 。


中英文術語對照
物件object
資料data
型態type
數值value
字串string
回傳值return value
變數variable
識別字identifier
字面常數literal
可變的mutable
不可變的immutable
複合資料型態compound data type
元素element
序對tuple
串列list
字典dictionary
垃圾收集garbage collection
屬性attribute
方法method
函數function




3 則留言:

Kaiching Chang 提到...

Python 的內建資料型態有
整數 int
浮點數 float
複數 complex
字串 str
字節 bytes
字節陣列 bytearray
串列 list
序對 tuple
集合 set
字典 dict

除了 int float complex 之外,其他都屬於複合資料型態。複合資料型態的元素有些可以刪除、新增,被稱為可變的,無法刪除、新增的就被稱為不可變的。

Jack 提到...

我想請問一下
為什麼在Python2.7內的a.__bool__()功能都不能使用!

Kaiching Chang 提到...

請用 Python 3 之後的直譯器, Python 2.x 的 int 型態並沒有內建 __bool__() 方法。