Python定義了豐富的數據類型,包括:html
數值型:int, float, complexpython
序列:(iterable) str, unicode, tuple, list, bytearray, buffer, xrangeexpress
集合:set, fronzeset編程
映射:dict函數式編程
文件:file函數
布爾值:True、False 和 bool() 函數,其中 bool() 函數將一個值轉變成布爾對象 True 或 False 。大數據
可調用對象:凡是可使用 x() 調用 x 的對象 x ,稱爲可調用的,x 能夠是類型、函數、類型中定義了 __call__() 方法的實例等。ui
None:spa
memoryview:memoryview對象是Python2.7的新增對象,容許Python代碼訪問一個支持緩衝協議(buffer protocol)的對象它的內部數據,而後能夠將其轉變爲字節字符串或字符對應ASCII值的列表等。3d
上下文管理器:上下文管理器用在 with 語句中,上下文管理協議(context management protocol)包括了 contextmanager.__enter__() 和 contextmanager.__exit__(exc_type, exc_val, exc_tb) 兩個方法。
裝飾器:裝飾器實際上就是高階函數,屬於函數式編程的範疇,得益於Python中「一切皆對象」的思想,裝飾器接受函數對象做爲參數,返回的則是一個修改後的函數對象。
其餘:
python中,模塊、類型、函數、實例、都是對象,可謂一切皆對象,此外,還有 code 對象, Type 對象即一個對象所屬的類型,經過 type() 函數來獲取;
類型 |
名稱 | 構造方法 | 介紹 |
basestring |
抽象的(不能實例化)的類型,是str和unicode類型的基類型,能夠經過isinstance(x, basestring)來判斷x是否是str或者unicode類型。 | ||
bool | bool(x) | 用來計算表達式x並返回x是True仍是False。bool是int的子類,只有兩個實例:True和False,True和False的值分別爲1和0,但str(True)和str(False)的值分別是'True'和'False'。 |
|
buffer | buffer(obj, offset=0, size=-1) | obj必須是string或者是array,該函數返回一個從offset開始,大小爲size的obj的部分只讀的buffer對象,若是size<0,或者obj的大小小於size,則會從offset開始直達obj結尾。 |
|
classmethod | 類方法 | classmethod(function) | 返回一個類方法,只能在類的定義中使用,能夠用@classmethod替代。 |
code | 代碼對象 | compile(source, filename, mode[, flags[, dont_inherit]]) | code 對象通常經過內置函數 compile() 方法建立,也能夠經過一個函數的func_code屬性查看,關於code對象的細節,在下文介紹。 |
complex | 複數 | complex(real, imag=0) |
|
dict | 字典 | dict(x={}) | 若是參數x是一個字典,那麼返回它的一個拷貝,參數x也能夠是一個可迭代對象,其中每個元素是一個二元組,如:x = [('a', 1), ('b', 2)] |
enumerate | 枚舉 | enumerate(iterable, start=0) | 從一個可迭代對象生成一個新的迭代器,這個迭代器的每個item都是一個二元組,二元組的首元是從start開始連續遞增的下標,而二元組的次元是參數可迭代對象從一個開始的內部元素。 |
open | 文件 | open(filename, mode='r', bufferzies=-1) | 以參數mode形式打開指定的filename,返回一個file對象。 |
float | 浮點型 | float(x) | 把數字或合適的字符串轉換成浮點數。 |
frozenset | frozenset(seq=[]) | 返回一個凍結集合對象,關於set和frozenset的討論請見 這篇博文。 |
|
int | 整型 | int(x[, radix]) | 將數字或合適的字符串轉換成整數,當x是一個字符串時,radix須要指定,表示轉換時的基數,默認是10,實際上轉換基數能夠介於2和36之間 |
list | 列表 | list(seq=[]) | 若是參數seq是一個列表,則返回它的拷貝;參數seq必須是一個可迭代對象,list()返回和這個可迭代對象具備相同順序相同元素的列表。 |
long | 長整型 | long(x [, radix]) | 將數字或合適的字符串轉換成長整數 |
object | object() | 返回一個最基本的類型的新實例。 |
|
property | 屬性 | property(fget=None, fset=None, fdel=None, doc=None) | 只能在類定義中使用,一般使用裝飾器@property |
reversed | reversed(seq) | 返回一個迭代器,這個迭代器和序列seq有着相反的元素對象,這個方法不會改變參數seq |
|
set | 集合 | set(seq=[]) | 返回一個set對象,set對象是可變的,若是seq是一個set對象,那麼set(seq)返回它的拷貝,關於內置類型set和frozenset的詳細討論參考這篇博文 |
slice | 切片 | slice([start, ] stop[, step]) | 返回一個slice對象, |
staticmethod | 靜態方法 | staticmethod(function) | 只在類定義中調用,返回一個靜態方法對象,或使用裝飾器@staticmethod |
str | plain string | str(obj) | 若是obj自己就是str類型的,則返回obj對象;不然,返回obj對象的面向讀者的形式,主要區別於repr面向python解釋器的形式 |
super | super(cls, obj) | 返回參數obj的父類的對象,obj必須是cls或cls子類的實例,這個方法主要用於調用父類的方法,這個函數只在方法代碼中調用 |
|
tuple | 元組 | tuple(seq) | 若是seq就是tuple對象,則返回它的拷貝;不然,返回一個和seq具備相同順序相同元素的tuple對象,seq必須是一個可迭代對象 |
type | type(obj) | type(x)等價於x.__class__,即x所屬的類型對象。 type 自己是一個內置的類型,也能夠做爲一個工廠對象,返回的是類型對象。Python中的類型對象只要支持相等與否的比較(equality comparison)和字符串表現形式便可。 按照面向對象的特色,類型對象又經常是可調用的,好比內置的 int, float, list 等等,調用這些對象能夠建立他們的實例,同時類型對象能夠被繼承(subclass),這都是類型的基本特徵。 |
|
unicode | unicode string | unicode(string [,codec, [, errors]]) | 返回一個unicode字符串對象 |
xrange | xrange([start, ] stop [,step=1]) | range()返回一個列表對象,xrange()則返回一個可迭代的xrange對象,這個對象不像range()返回的list那樣將全部的元素都事先生成好放在內存中,而是在迭代的過程當中每次生成一個,從而對於遍歷大數據量的數字序列時,xrange在內存上具備顯著優點。Python 3之後,再也不使用xrange這個概念,而是將range基於Python 2中的xrange改良,使得Python 3 中range的功能更強大。 |
Python中的 code 對象
咱們首先看一下內置函數 compile() 的介紹:
compile(source, filename, mode[, flags[, dont_inherit]]) -> code object Compile the source string (a Python module, statement or expression) into a code object that can be executed by the exec statement or eval(). The filename will be used for run-time error messages. The mode must be 'exec' to compile a module, 'single' to compile a single (interactive) statement, or 'eval' to compile an expression. The flags argument, if present, controls which future statements influence the compilation of the code. The dont_inherit argument, if non-zero, stops the compilation inheriting the effects of any future statements in effect in the code calling compile; if absent or zero these statements do influence the compilation, in addition to any features explicitly specified.
總結起來就是:
compile()函數用於構造一個 code 對象,code對象能夠做爲 exec() 和 eval() 的參數;
對於任意一個Python函數而言,其 func_code 屬性就是一個 code 對象,該對象是不可調用的,可是能夠將它綁定給另外一個具備相同參數個數的函數對象,從而建立一個新的函數對象:
>>> f = lambda x, y: x + y >>> f.func_code <code object <lambda> at 0000000001D74530, file "<stdin>", line 1> >>> code_obj = f.func_code >>> def g(x, y): pass ... >>> g.func_code = code_obj >>> g(1, 9) 10
本來咱們是沒有定義函數 g 的函數體的,可是經過替換它的 func_code 屬性,能夠將不可調用的 code 對象替換成一個可調用的函數,是否是有一種金蟬脫殼的感受呢。
Python的 types 模塊
types模塊的屬性是 Python的內置類型,包括:
>>> dir(types) ['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__builtins__', '__doc__', '__file__', '__name__', '__package__']
如何知道這些屬性實際上是 Python 的內置類型呢?
例如:
>>> types.DictionaryType <type 'dict'> >>> types.DictType <type 'dict'> >>> type({}) <type 'dict'>
可見,types.DictType 和 types.DictionaryType 其實就是內置類型 dict,也就是 type({}) 。
Python 類型的方法查找路徑(Method Resolution Order)
Python支持多重繼承,當引用一個繼承了多個類型的實例的屬性時,如何肯定屬性、方法的查找順序,稱爲方法查找路徑。
Python中一個繼承自多個類型的類使用一種稱爲 C3 的方法查找路徑(The Python 2.3 Method Resolution Order),經過一個自定義類型的 __mro__ 屬性能夠查看該類型的方法查找路徑:
>>> class D(object): ... d = 100 ... >>> class B(D): ... pass ... >>> class C(D): ... pass ... >>> class A(B, C): pass ... >>> A.__mro__ (<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.D'>, <type 'object'>)
在Python中,只能查看一個類型(而不是實例)的 __mro__ 屬性,該屬性是隻讀的,其中各個類型顯示的順序,就是當訪問該類型的屬性、方法時查找的順序。
對於一個實例而言,若是實例中綁定了某個屬性,那麼在屬性查找時,實例綁定的屬性先於類中定義的屬性。
Python 中的 metaclass
Python中 type 和 object 的關係與區別
Python 中有兩個很是有趣的概念——type 和 object,這裏梳理一下他們的關係:
怎麼樣,夠暈吧,下面的例子能夠解釋他們之間的關係,
例如:
>>> isinstance(object, type) True >>> issubclass(type, object) True >>> type(object) <type 'type'> >>> type(type) <type 'type'> >>> object.__base__ >>> type.__base__ <type 'object'> >>>
這裏掛上一張示意圖,其中實線箭頭表明類型繼承,虛線箭頭則表明實例化,從而能夠看出其中的一致性。
關於這個雞生蛋蛋生雞的有趣討論,能夠參考:http://www.cnblogs.com/txw1958/archive/2012/11/30/Python-Types-and-Objects.html
全部的序列(Sequence)都是可迭代的(Iterable),可是可迭代對象卻不止Sequence: