對象自省
自省(introspection),在計算機編程領域裏,是指在運行時來判斷一個對象的類型的能力。它是Python的強項之一。Python中所有一切都是一個對象,而且我們可以仔細勘察那些對象。Python還包含了許多內置函數和模塊來幫助我們。
dir
在這個小節裏我們會學習到dir以及它在自省方面如何給我們提供便利。
它是用於自省的最重要的函數之一。它返回一個列表,列出了一個對象所擁有的屬性和方法。這裏是一個例子:
my_list = [1, 2, 3]
dir(my_list)
# Output: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
# '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
# '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__',
# '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__',
# '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
# '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__',
# '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop',
# 'remove', 'reverse', 'sort']
上面的自省給了我們一個列表對象的所有方法的名字。當你沒法回憶起一個方法的名字,這會非常有幫助。如果我們運行dir()而不傳入參數,那麼它會返回當前作用域的所有名字。
type和id
type函數返回一個對象的類型。舉個例子:
print(type(''))
# Output: <type 'str'>
print(type([]))
# Output: <type 'list'>
print(type({}))
# Output: <type 'dict'>
print(type(dict))
# Output: <type 'type'>
print(type(3))
# Output: <type 'int'>
id()函數返回任意不同種類對象的唯一ID,舉個例子:
name = "Yasoob"
print(id(name))
# Output: 139972439030304
inspect模塊
inspect模塊也提供了許多有用的函數,來獲取活躍對象的信息。比方説,你可以查看一個對象的成員,只需運行:
import inspect
print(inspect.getmembers(str))
# Output: [('__add__', <slot wrapper '__add__' of ... ...
還有好多個其他方法也能有助於自省。如果你願意,你可以去探索它們。