【讀書筆記】深入理解Python特性(四)

目錄

1. 實例方法、類方法和靜態方法

2. 字典(也稱爲映射、散列表、查找表、關聯數組)

3. 數組數據結構

4. 記錄、結構體和純數據對象


1. 實例方法、類方法和靜態方法

  • Python在使用點語法調用靜態方法時不會傳入self或者cls參數,從而限制了靜態方法訪問的內容。
  • 使用@classmethod定義的類方法可以創建工廠函數,如果將來類重命名,就不用變更工廠方法中的構造函數名稱。

2. 字典(也稱爲映射、散列表、查找表、關聯數組)

  • OrderedDict能記住鍵的插入順序
import collections
collections.OrderedDict(one=1, two=2, three=3)
  • 通過Key訪問dict,當Key不存在時,會引發‘KeyError’異常。爲了避免這種情況的發生,可以使用collections類中的defaultdict()方法來爲字典提供默認值。
import collections
dd = collections.defaultdict(list)
dd['dogs'].append('Rufus')

如果使用原始dict,在使用dd['dogs'].append()時會出現異常。

  • ChainMap:可以將多個dict整合到一個map中,查找時逐個查找底層map,直到找到一個符合條件的鍵。對ChainMap進行插入、更新和刪除操作,只會作用於其中第一個map
>>> from collections import ChainMap
>>> dict1 = {'one':1, 'two':2}
>>> dict2 = {'three':3, 'four':4}
>>> chain = ChainMap(dict1, dict2)
>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})
>>> chain['three']
3
>>> chain['one']
1
>>> chain['missing']
KeyError: 'missing'
>>>
  • type.MappingProxyType(Python3.3+):用於創建只讀字典。比如說,如果希望返回一個字典表示類或者模塊的內部狀態,同時禁止向該對象寫入內容,此時就可以使用MappingProxyType。
>>> from types import MappingProxyType
>>> writable = {'one':1, 'two':2}
>>> read_only = MappingProxyType(writable)
>>> read_only['one']
1
# 代理是隻讀的
>>> read_only['one'] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment
# 更新原字典也會影響代理
>>> writable['one'] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})

3. 數組數據結構

  • array.array是單一類型的可變數組,原型:array.array(typecode, [initializer]),typecode表示元素類型,可通過array.typecodes查看所有類型
  • str是含有unicode字符的不可變數組
  • bytes是含有單字節的不可變數組,元素爲[0,255]之間的整數。
>>> arr = bytes((0, 1, 2, 3))
>>> arr[1]
1
>>> arr
b'\x00\x01\x02\x03'
>>> bytes((0, 300))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: bytes must be in range(0, 256)
>>> arr[1] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment
>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object doesn't support item deletion
>>>
  • bytearray是含有單字節的可變數組

4. 記錄、結構體和純數據對象

  • typing.NamedTuple:相比於colletions.namedtuple,typing.NamedTuple的主要特點在於用新語法來定義記錄類型並支持類型註解。(詳細例子見書P98)
  • struct.Struct:不太明白具體有什麼用,後面瞭解了再更新

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章