Python學習筆記27:類序列物件
在Python中,通常會把符合一定“行為”的物件稱呼為“類某某物件”,比如類檔案物件,就是說實作了背景關系協議,可以在with/as中使用的物件,其行為與檔案操作類似,
對應的,我們也可以創建一個類序列物件,指的是某一類可以像序列容器那樣進行操作的物件,
這里使用和《Fluent Python》中所舉的多維向量一致的例子,可能在具體命名和實作上有出入,但整體思路一致,都是為了說明如何把一個Python學習筆記26:符合Python風格的物件所舉例的二維向量擴展到多維,并且符合序列的特性,
VectorN
我們的首要作業是創建一個多維向量,并且實作之前二維向量的大多數基本功能,
import array
class VectorN():
typeCode = 'd'
def __init__(self, iterable):
self.__contents = array.array(self.typeCode, iterable)
def __iter__(self):
return iter(self.contents)
def __repr__(self):
cls = type(self)
clsName = cls.__name__
if len(self.contents) == 0:
return "{}()".format(clsName)
string = str(self.contents)
numbersStr = string[string.find('[')+1:-2]
return "{}({})".format(clsName, numbersStr)
def __str__(self):
if len(self.contents) == 0:
return "()"
string = str(self.contents)
numbersStr = string[string.find('[')+1:-2]
return "({})".format(numbersStr)
def __eq__(self, other):
return tuple(self) == tuple(other)
def __abs__(self):
pass
def __bool__(self):
pass
def __bytes__(self):
return self.typeCode.encode('UTF-8')+bytes(self.contents)
def angle(self):
pass
def __format__(self, format_spec):
pass
@classmethod
def fromBytes(cls, bytesVectorN):
typeCode = chr(bytesVectorN[0])
arrayVectorN = array.array(typeCode)
arrayVectorN.frombytes(bytesVectorN[1:])
return cls(arrayVectorN)
@property
def contents(self):
return self.__contents
def __hash__(self):
pass
這里基本是對照著之前我們創建的Vector類進行創建的,部分比較棘手的方法先使用pass進行占位,稍后我們重點討論如何實作,
這里有這么幾點需要著重說明:
建議對照Python學習筆記26:符合Python風格的物件中文末的
Vector類完整代碼進行理解,
- 因為是多維向量,所以初始化方法中使用
array來實作底層存盤,相應的,接收引數也改為一個可迭代物件, __iter__方法我們可以直接利用array的迭代器直接回傳,關于迭代器的詳細內容我們將在以后進行討論,__repr__和__str__我們都利用array的字串形式進行裁切后組合成我們需要的形式,這里其實可以更簡單地將其轉化為元組后直接使用元組地字串形式,但多一步轉化也意味著多一步性能浪費,對于多維陣列來說,其多余的空間開銷也的確值得注意,所以這里使用了字串裁切的方式,- 如同我們在第三點中說的,
__eq__這里沿用Vector中的做法也存在額外的性能浪費,這個我們在稍后將詳細說明,并且會給出優化方案, - 關于位元組序列化和反位元組序列化的方法
__bytes__和fromBytes幾乎和Vector中的沒有區別,只不過在反位元組序列化的時候,return cls(arrayVectorN)沒有使用*,這是因為我們在第一點中所說的,現在初始化方法只接收一個可迭代物件, - 使用
property裝飾器的目的和之前一樣,是為了后續實作散列,
現在我們簡單測驗一下:
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
print(vectorN)
print(repr((vectorN)))
vectorN2 = VectorN(l)
print(vectorN == vectorN2)
vectorN3 = VectorN([1, 2, 3])
print(vectorN == vectorN3)
print(bytes(vectorN))
vectorNBytes = bytes(vectorN)
vectorN4 = VectorN.fromBytes(vectorNBytes)
print(vectorN == vectorN4)
# (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
# VectorN(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
# True
# False
# b'd\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x08@\x00\x00\x00\x00\x00\x00\x10@\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x00\x18@\x00\x00\x00\x00\x00\x00\x1c@\x00\x00\x00\x00\x00\x00 @\x00\x00\x00\x00\x00\x00"@\x00\x00\x00\x00\x00\x00$@'
# True
這里還有一個細節需要優化,因為我們這里是多維向量,所以如果包含的維度很大,通過__str__和__repr__回傳的字串對控制臺顯示就很不友好,事實上就像我們之前所說的,__repr__只是用于開發者除錯的,完全沒有必要顯示所有資訊,我們這里可以學習Python官方組件在類似情況下的輸出,對于多余資訊用...來簡化顯示,
def __repr__(self):
cls = type(self)
clsName = cls.__name__
if len(self.contents) == 0:
return "{}()".format(clsName)
string = reprlib.repr(self.contents)
numbersStr = string[string.find('[')+1:-2]
return "{}({})".format(clsName, numbersStr)
這里只要使用reprlib模塊就可以簡單實作,
我們看效果:
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
print(repr(vectorN))
# VectorN(1.0, 2.0, 3.0, 4.0, 5.0, ...)
序列化
正如我們之前說的,類檔案物件是要實作背景關系協議,而類序列物件自然也要實作對應的協議,
這里的協議很像是傳統編程語言中的介面,在Java中,實作了相應介面自然也可以將物件應用到所有使用該介面的用途中,而Python中的協議并不完全是類似介面的存在,其關鍵因素是Python中的協議僅代表一種約定,并不具有強制性,
我們用序列的實作協議進行類比,我們先來看如何將VectorN“變成”一個序列:
def __getitem__(self, index):
return self.contents[index]
def __len__(self):
return len(self.contents)
很簡單對不對,只要實作__getitem__和__len__就可以了,而且我們還可以通過委托給內含的array來完成具體作業,
進行一下簡單測驗:
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
print(vectorN[0])
print(vectorN[2])
print(len(vectorN))
# 1.0
# 3.0
# 10
事實上,并不是每一個需要“變現地像個序列”的類序列物件都要實作__getitem__和__len__,如果你只會用到len(obj),則只實作__len__是可行的,相似的,如果你只用切片,那不實作__len__也可以,
所以說Python中的協議并不具有強制性,它只是指出完整協議需要實作哪些方法,而具體使用中你完全可以按照實際需求僅實作其中的一部分,這是符合Python風格的,Python的設計本身就處處體現著實用性的思想,
我們再說回VectorN,看似其表現的像個序列,但是如果我們使用更多的切片功能:
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
print(vectorN[:])
print(vectorN[2:-1])
# array('d', [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0])
# array('d', [3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
看出問題了么?
切片得到的子序列并不是VectorN型別,而是array,這顯然不是我們想要的,如果子序列和原始序列不是同一型別,那我們就不能針對子序列進行原始序列的操作,這很不Python,
所以我們接下來討論如何進一步改造以實作完整的切片支持,
切片
切片原理
我們先來探索一下Python是如何實作切片的,
為了觀察程式運行時Python解釋器給__getitem__傳入的實際引數,我們對VectorN做如下修改:
def __getitem__(self, index):
return index
運行測驗程式:
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
print(vectorN[1])
print(vectorN[:])
print(vectorN[1:5])
print(vectorN[1:10:2])
print(vectorN[1:5, 2])
# 1
# slice(None, None, None)
# slice(1, 5, None)
# slice(1, 10, 2)
# (slice(1, 5, None), 2)
不難觀察到以下規律:
- 當切片方式是單個數字的時候,傳入的引數
index就是單數字索引值, - 當切片方式是
[:]的時候,index引數是一個slice物件,具體是slice(None,None,None), - 當切片方式是
[1:5]的時候,引數是slice(1,5,None), - 特別的是,當切片是類似
NumPy中的那種多維切片[1:5],2的時候,index引數是一個包含slice物件的元組,
現在我們還需要知道如何從slice物件中提取start\stop\step,
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
sli = slice(1,10,2)
print(dir(sli))
print(sli)
print(sli.start, sli.stop, sli.step)
sli2 = slice(1, None, None)
print(sli2.start, sli2.stop, sli2.step)
# ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
# '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'indices', 'start', 'step', 'stop']
# slice(1, 10, 2)
# 1 10 2
# 1 None None
通過一些簡單試探,我們可以知道如何提取start\stop\step,理論上我們現在就可以改造__getitem__方法了,只不過麻煩一些,需要考慮這些值為None的情況要如何處理,
事實上情況遠比這要復雜,因為Python的切片操作是支持反向的,也就是說你還要考慮step為負數,或者start和stop為負數的情況,
這無疑是讓人抓狂的,為了處理這些Python已經干的很好的問題自己去再實作一套邏輯?
那顯然是個糟糕的提議,
indices
事實上,slice實體有一個方法indices,正可以解決這個問題:
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
sli = slice(1,10,2)
print(help(sli.indices))
# Help on built-in function indices:
# indices(...) method of builtins.slice instance
# S.indices(len) -> (start, stop, stride)
# Assuming a sequence of length len, calculate the start and stop
# indices, and the stride length of the extended slice described by
# S. Out of bounds indices are clipped in a manner consistent with the
# handling of normal slices.
# None
只要傳入序列長度,indeces方法就會自動計算出實際的相應起始、終止索引和步進,完全不需要我們自行計算,
實作
索引的問題解決了,我們還需要考慮非法輸入的問題,比如像上面那樣多維切片,我們要如何處理,該不該報例外,該使用何種例外,提示資訊又要寫什么,
這個問題我們完全可以參考Python官方:
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
l[:,2]
# Traceback (most recent call last):
# File "D:\workspace\python\test\test.py", line 4, in <module>
# l[:,2]
# TypeError: list indices must be integers or slices, not tuple
到了愉快的抄答案時間了,
好了,現在完事具備,我們來改寫__getitem__:
def __getitem__(self, index):
cls = type(self)
if isinstance(index, numbers.Integral):
return self.contents[index]
elif isinstance(index, slice):
start,stop,step = index.indices(len(self))
subArray = self.contents[start:stop:step]
return cls(subArray)
elif isinstance(index, tuple):
raise TypeError("list indices must be integers or slices, not tuple")
else:
raise TypeError("list indices must be integers or slices")
測驗一下:
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
print(vectorN[1])
print(vectorN[:])
print(vectorN[1:5])
print(vectorN[1:10:2])
print(vectorN[1:5, 2])
# 2.0
# (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
# (2.0, 3.0, 4.0, 5.0)
# (2.0, 4.0, 6.0, 8.0, 10.0)
# Traceback (most recent call last):
# File "D:\workspace\python\test\test.py", line 8, in <module>
# print(vectorN[1:5, 2])
# File "D:\workspace\python\test\vectorN.py", line 71, in __getitem__
# raise TypeError("list indices must be integers or slices, not tuple")
# TypeError: list indices must be integers or slices, not tuple
事實上,在呼叫array切片的時候,我們可以不使用start:stop:step的方式,可以直接使用slice實體,array可以正確進行處理:
elif isinstance(index, slice):
# start,stop,step = index.indices(len(self))
# subArray = self.contents[start:stop:step]
subArray = self.contents[index]
return cls(subArray)
但之前我們做的探索并非無用功,比如我們底層如果是自己實作,而非是利用已有容器,那就很有必要獲取正確的索引和步進,此外我們也對slice實體有了更多的了解不是嗎,
動態存取屬性
在之前的Vector類中,我們通過使用裝飾器property實作了對私有屬性的讀取和保護,那在VectorN中,如果我們需要以vectorN.x\vectorN.y等方式讀取前幾個元素是不是也可以用類似方法?
答案當然是可以的,但是對兩三個元素我們可以如此處理,如果是多個元素也要一一創建方法并用property裝飾?
當然不用,Python提供一個魔術方法__getattr__正是用于處理此類問題,
注意,Python中還有一個
__getattribute__方法,這兩個方法效果完全不同,不要搞混,
__getattr__
在實作__getattr__之前,我們還要搞清楚如果訪問的屬性超過合理范圍,需要怎么顯示錯誤,
當然是繼續抄官方了:
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
l[13]
# Traceback (most recent call last):
# File "D:\workspace\python\test\test.py", line 4, in <module>
# l[13]
# IndexError: list index out of range
現在來實作__getattr__:
def __getattr__(self, name):
attrStr = "xyzt"
if len(name) == 1:
index = attrStr.find(name)
if 0 <= index < len(self):
return self.contents[index]
raise IndexError("list index out of range")
測驗一下:
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
print(vectorN.x)
print(vectorN.y)
print(vectorN.z)
# 1.0
# 2.0
# 3.0
__getattr__的運行機制是:當Python解釋器試圖獲取一個實體屬性,但是實體字典中沒有的時候,會在其類中查找類屬性,如果類屬性也沒有,就會在父類中查找,如果父類中也沒有,就會通過__getattr__函式獲取,
真實情況比這更復雜,會在以后進行討論,
這種屬性訪問方式目前看來似乎沒有問題,但是我們一旦進行賦值操作:
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
print(vectorN.x)
vectorN.x = 2
print(vectorN.x)
print(vectorN[0])
# 1.0
# 2
# 1.0
當我們試圖進行賦值操作的時候,奇怪的事情發生了,
事實上只要我們對實際上并不存在的屬性進行賦值,就會給實體添加一個新的屬性,這就會導致我們原來設定的__getattr__機制完全失效,后續的讀取和賦值操作都只會針對新產生的實體屬性,
要解決這個問題我們就要實作__setattr__,
__setattr__
事實上__setattr__和__getattr__經常成對出現,如果只設定了其中之一,很可能會出現一些意料之外的bug,
def __setattr__(self, name, value):
cls = type(self)
if len(name) == 1:
msg = ""
if name in cls.attrStr:
msg = "readonly attribute {}".format(name)
else:
pass
raise AttributeError(msg)
super().__setattr__(name, value)
因為
__setattr__也要使用attrStr,所以改為類屬性,這里不多做演示,
用同樣的測驗程式進行測驗:
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
print(vectorN.x)
vectorN.x = 2
print(vectorN.x)
print(vectorN[0])
# 1.0
# Traceback (most recent call last):
# File "D:\workspace\python\test\test.py", line 5, in <module>
# vectorN.x = 2
# File "D:\workspace\python\test\vectorN.py", line 97, in __setattr__
# raise AttributeError(msg)
# AttributeError: readonly attribute x
散列和快速等值測驗
我們在Vector中使用位運算^來實作哈希演算法,相應的,這里我們同樣可以通過累積異或來實作多維向量的哈希演算法,
這里的哈希演算法就是散列演算法,一個意思,因為"hash"更貼近音譯,所以我更習慣用哈希稱呼,
reduce
提到累積運算,高階函式reduce當然會是首先想到的,
def __hash__(self): hashes = [hash(num) for num in self.contents] return functools.reduce(operator.xor, hashes, 0)
這里需要注意的是,reduce的第三個引數是0,這是為了避免第二個引數為慷訓者僅有一個元素時候可能出現的bug,但這個引數需要注意的是并不能無腦設定為0,這個引數是和第一個引數的具體運算方式密切相關的,簡單來說它要符合相應運算的冪等性,如果運算是+,則是0,因為0無論加多少次還是0,如果運算是*,則是1,因為1無論被乘以多少次還是1,對于異或,則是0,因為異或操作的準則為“相同為0,相異為1”,所以0被異或多少次依然為0,
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
print(hash(vectorN))
vectorN2 = VectorN([1,2,3])
print(hash(vectorN2))
vectorSet = set()
vectorSet.add(vectorN)
vectorSet.add(vectorN2)
# 11
# 0
通過上面的測驗我們可以知道,VectorN已經被我們成功散列化,它是可散列的了,
eq優化
我們在之前提到過,在實作==運算子多載的時候存在性能浪費,我們這里進行優化,
如果是用其它傳統變成語言的方式,我會這么優化:
def __eq__(self, other):
if len(self) != len(other):
return False
else:
for i in range(len(self)):
if self[i] != other[i]:
return False
return True
測驗一下:
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
vectorN2 = VectorN([1,2,3])
print(vectorN == vectorN2)
vectorN3 = VectorN(l)
print(vectorN == vectorN3)
OK,沒有任何問題,但是吹毛求疵的人會說這很不Python,
我們看一下用Python的方式要怎么實作,
zip
這里我們需要用到一個Python內建函式zip,
zip是為了解決如何同時遍歷多個可迭代物件的問題:
a = [i for i in range(10)]
b = [i for i in range(1, 9)]
for num1, num2 in zip(a, b):
print(num1, num2)
# 0 1
# 1 2
# 2 3
# 3 4
# 4 5
# 5 6
# 6 7
# 7 8
我們需要注意到的是,zip在處理多個可迭代物件的時候,如果這些可迭代對象包含的元素個數并不相同,則會在遍歷完最少元素的可迭代物件后立即結束遍歷,不會有任何例外或者報錯,就像示例中一樣,即使a還有兩個元素沒有輸出,遍歷也結束了,
相應的,還有一個zip_longest:
from itertools import zip_longest
a = [i for i in range(10)]
b = [i for i in range(1, 9)]
for num1, num2 in zip_longest(a, b, fillvalue=-1):
print(num1, num2)
# 0 1
# 1 2
# 2 3
# 3 4
# 4 5
# 5 6
# 6 7
# 7 8
# 8 -1
# 9 -1
zip_longest需要匯入itertools模塊,且使用的時候需要指定一個填充值fillvalue,
當有可迭代物件遍歷完,但其他物件還沒有的時候,缺少的相應元素就會使用填充值進行填充,就像示例中的-1那樣,
我們現在用zip來改寫:
def __eq__(self, other):
if len(self) != len(other):
return False
else:
for num1, num2 in zip(self, other):
if num1 != num2:
return False
return True
看似沒有改變多少,但其實我們已經摒棄了實際下標,而是使用遍歷器同時遍歷兩個容器,這已經是相當大的進步,即使兩個容器下標不同,但只要有相同的元素個數,以及元素能一一對應相等,就可以認為是相等的兩個容器,這無疑比使用下標更為靈活,
我們可以進一步Python化:
def __eq__(self, other):
if len(self) != len(other):
return False
else:
return all(num1 == num2 for num1,num2 in zip(self, other))
all函式的參考可以看這里,
甚至是這樣:
def __eq__(self, other):
return len(self) != len(other) and all(num1 == num2 for num1,num2 in zip(self, other))
這無疑比我們一開始的寫法更Python,更“政治正確”,
但在我看來,如果你時間充裕,而且對撰寫更Python化的代碼更癡迷,你完全可以追求此類的寫法,但如果你時間緊迫,且對離散數學很頭大,那完全可以跳過此類的寫法,畢竟,Python的真正奧義是實用,
終于到我們最后一個議題了,
格式化
在Vector中我們使用格式化進行極坐標輸出,對應到多維向量,則是“球面坐標”或“超球面坐標”,
球面坐標的解釋可以看這里,
要實作到球面坐標系的轉化,我們要實作對n維向量的極坐標系計算,具體數學公式我就不細究了,老實說,我現在還能看懂極坐標就已經很難為自己了orz,所以我這里照抄《Fluent Python》中的代碼,
這里先需要實作多維向量的求模:
def __abs__(self):
return math.sqrt(sum(x*x for x in self))
再實作求坐標轉換演算法:
def angle(self, n):
r = math.sqrt(sum(x*x for x in self[n:]))
a = math.atan2(r, self[n-1])
if (n == len(self)-1) and (self[-1]<0):
return math.pi * 2 -a
else:
return a
def angles(self):
return (self.angle(n) for n in range(1, len(self)))
最后實作格式化:
def __format__(self, format_spec):
if format_spec.endswith('h'):
format_spec = format_spec[:-1]
coords = itertools.chain([abs(self)],self.angles())
outer_fmt = "<{}>"
else:
coords = self
outer_fmt = "({})"
components = (format(c, format_spec) for c in coords)
return outer_fmt.format(','.join(components))
測驗一下:
from vectorN import VectorN
l = [i for i in range(1, 11)]
vectorN = VectorN(l)
print(format(vectorN,'.2fh'))
# <19.62,1.52,1.47,1.42,1.36,1.30,1.23,1.15,1.03,0.84>
老實說我也不知道結果是否正確=,=,就當是正確的好了,
好了,以上就是這次的全部內容,能看到這里的童鞋值得鼓勵,
最后附上目前為止VectorN的完整定義,便于查看:
import array
import numbers
import functools
import operator
import math
import itertools
import reprlib
class VectorN():
typeCode = 'd'
attrStr = "xyzt"
def __init__(self, iterable):
self.__contents = array.array(self.typeCode, iterable)
def __iter__(self):
return iter(self.contents)
def __repr__(self):
cls = type(self)
clsName = cls.__name__
if len(self.contents) == 0:
return "{}()".format(clsName)
string = reprlib.repr(self.contents)
numbersStr = string[string.find('[')+1:-2]
return "{}({})".format(clsName, numbersStr)
def __str__(self):
if len(self.contents) == 0:
return "()"
string = str(self.contents)
numbersStr = string[string.find('[')+1:-2]
return "({})".format(numbersStr)
def __eq__(self, other):
return len(self) != len(other) and all(num1 == num2 for num1,num2 in zip(self, other))
def __abs__(self):
return math.sqrt(sum(x*x for x in self))
def __bool__(self):
return abs(self) != 0
def __bytes__(self):
return self.typeCode.encode('UTF-8')+bytes(self.contents)
@classmethod
def fromBytes(cls, bytesVectorN):
typeCode = chr(bytesVectorN[0])
arrayVectorN = array.array(typeCode)
arrayVectorN.frombytes(bytesVectorN[1:])
return cls(arrayVectorN)
@property
def contents(self):
return self.__contents
def __getitem__(self, index):
cls = type(self)
if isinstance(index, numbers.Integral):
return self.contents[index]
elif isinstance(index, slice):
# start,stop,step = index.indices(len(self))
# subArray = self.contents[start:stop:step]
subArray = self.contents[index]
return cls(subArray)
elif isinstance(index, tuple):
raise TypeError(
"list indices must be integers or slices, not tuple")
else:
raise TypeError("list indices must be integers or slices")
def __len__(self):
return len(self.contents)
def __getattr__(self, name):
cls = type(self)
if len(name) == 1:
index = cls.attrStr.find(name)
if 0 <= index < len(self):
return self.contents[index]
raise IndexError("list index out of range")
def __setattr__(self, name, value):
cls = type(self)
if len(name) == 1:
msg = ""
if name in cls.attrStr:
msg = "readonly attribute {}".format(name)
else:
pass
raise AttributeError(msg)
super().__setattr__(name, value)
def __hash__(self):
hashes = [hash(num) for num in self.contents]
return functools.reduce(operator.xor, hashes, 0)
def angle(self, n):
r = math.sqrt(sum(x*x for x in self[n:]))
a = math.atan2(r, self[n-1])
if (n == len(self)-1) and (self[-1]<0):
return math.pi * 2 -a
else:
return a
def angles(self):
return (self.angle(n) for n in range(1, len(self)))
def __format__(self, format_spec):
if format_spec.endswith('h'):
format_spec = format_spec[:-1]
coords = itertools.chain([abs(self)],self.angles())
outer_fmt = "<{}>"
else:
coords = self
outer_fmt = "({})"
components = (format(c, format_spec) for c in coords)
return outer_fmt.format(','.join(components))
又是在一個沒有暖氣的陰冷北方下午完成了這篇博客,你們對我的CSDN博客的關注評論和點贊是我繼續更新的最大動力,在這里再次感謝,
對我的博客有任何看法和內容糾錯,都可以在下面留言,
謝謝閱讀,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/281645.html
標籤:python
上一篇:python基礎知識(持續更新)
