Python內建型別總共28個,這些型別本身也是一種物件(在Python程式語言裡面所有的都是物件),稱為型別物件(type objects),使用type()函式可以知道物件的型別是什麼型別物件。
在Python的標準程式庫中,types模組定義部分型別的型別名稱,我們可以使用這些型別名稱取得型別物件,像是types.IntType就是取的int型別物件,注意到並不是所有的型別物件都有定義名稱,只有16個型別有定義名稱,整理如下表。
| 內建型別物件 | 型別名稱 |
| basestring | |
| bool | BooleanType |
| buffer | BufferType |
| bytearray | |
| bytes (bytes型別是Python 3.0才正式新增, 2.x等於str) | |
| classmethod | |
| complex | ComplexType |
| dict | DictType, DictionaryType |
| enumerate | |
| file | FileType |
| float | FloatType |
| frozenset | |
| int | IntType |
| list | ListType |
| long | LongType |
| memoryview | |
| object | ObjectType |
| property | |
| reversed | |
| set | |
| slice | SliceType |
| staticmethod | |
| str | StringType |
| super | |
| tuple | TupleType |
| type | TypeType |
| unicode | UnicodeType |
| xrange | XRangeType |
另外在內建常數的部分,types模組定義定義3個型別名稱,分別是:
| 內建常數 | 型別名稱 |
| None | NoneType |
| NotImplemented | NotImplementedType |
| Ellipsis | EllipsisType |
剩下的型別名稱則是常用的物件,因此types模組定義這些物件的型別名稱,總共17個
- BuiltinFunctionType
- BuiltinMethodType
- ClassType
- CodeType
- DictProxyType
- FrameType
- FunctionType
- GeneratorType
- GetSetDescriptorType
- InstanceType
- LambdaType
- MemberDescriptorType
- MethodType
- ModuleType
- StringTypes
- TracebackType
- UnboundMethodType
列出內建型別的程式碼
if __name__ == "__main__":
import types
for item in dir(__builtins__):
attr = getattr(__builtins__, item)
if type(attr) is types.TypeType and \
not issubclass(attr, BaseException):
print attr
###
沒有留言:
張貼留言