__builtins__ 包含 Python 核心內建函數、例外與型別,無需匯入即可使用。本文精選實用且易被忽視的進階用法,提升程式碼彈性與表達力。
isinstance(obj, basestring) # Python 2: str + unicode
isinstance(obj, (str, unicode)) # 等價寫法
isinstance(obj, (int, float, long)) # 數值型別元組
write = getattr(obj, 'write', sys.stdout.write)
# obj 無 write 屬性時回傳 sys.stdout.write
# type(name, bases, dict) -> 新類別
Point = type('Point', (object,), {'x': 0, 'y': 0})
p = Point()
p.x, p.y # (0, 0)
# 動態加入方法
def tostr(self): return '(%s,%s)' % (self.x, self.y)
Point.__str__ = tostr
def init(self, x, y): self.x, self.y = x, y
Point.__init__ = init
p2 = Point(6, 8)
print p2 # (6,8)
issubclass(bool, int) # True
# True == 1, False == 0 可直接參與運算
import numbers
isinstance(3, numbers.Number) # True
isinstance(3.14, numbers.Number) # True
isinstance(1+2j, numbers.Number) # True
type(None) == types.NoneType # True
# None 是單例常數,不可重新賦值
# iter(callable, sentinel) -> 迭代器
def getrand():
import random
return random.randint(1, 100)
for i in iter(getrand, 50):
print i, # 印出第一次出現 50 前的所有隨機數
# 每次呼叫 getrand(),直到回傳 50 停止(不包含 50)
BaseException # 所有例外基類
Exception # 非系統退出類例外基類
# KeyboardInterrupt, SystemExit 繼承 BaseException 而非 Exception
| 函數 | 說明 |
|---|---|
locals() | 當前區域符號表 (dict) |
globals() | 全域符號表 (dict) |
vars() | 等同 locals();vars(obj) 等同 obj.__dict__ |
dir() | 無參數等同 locals().keys();有參數依物件型別回傳屬性列表 |
for i, name in enumerate(['C','C++','CSharp','Java','Python'], 1):
print '%d.%s' % (i, name)
# 1.C
# 2.C++
# 3.CSharp
# 4.Java
# 5.Python