Python3.6首次發(fā)布于2016年,盡管它已經(jīng)發(fā)布了很長一段時(shí)間,但它引入的許多特性都沒有得到充分利用,而且相當(dāng)酷。下面是其中的三個(gè)。
分隔數(shù)字常數(shù)
快回答哪個(gè)更大,10000000還是200000?你在看代碼時(shí)能正確回答嗎?根據(jù)當(dāng)?shù)氐牧?xí)慣,在寫作中,你會(huì)用10,000,000或10.000.000來表示第一個(gè)數(shù)字。問題是,Python使用逗號(hào)和句號(hào)是用于其他地方。
幸運(yùn)的是,從Python3.6開始,你可以使用下劃線來分隔數(shù)字。這在代碼中和使用字符串的int()轉(zhuǎn)換器時(shí)都可以使用:
importmath
math.log(10_000_000)/math.log(10)
7.0
math.log(int("10_000_000"))/math.log(10)
7.0
Tau是對(duì)的
45度角用弧度表示是多少?一個(gè)正確的答案是π/4,但這有點(diǎn)難記。記住45度角是一個(gè)八分之一的轉(zhuǎn)角要容易得多。正如TauManifesto所解釋的,2π,稱為Τ,是一個(gè)更自然的常數(shù)。
在Python3.6及以后的版本中,你的數(shù)學(xué)代碼可以使用更直觀的常數(shù):
print("Tanofaneighthturnshouldbe1,got",round(math.tan(math.tau/8),2))
print("Cosofansixthturnshouldbe1/2,got",round(math.cos(math.tau/6),2))
print("Sinofaquarterturnshouldbe1,go",round(math.sin(math.tau/4),2))
Tanofaneighthturnshouldbe1,got1.0
Cosofansixthturnshouldbe1/2,got0.5
Sinofaquarterturnshouldbe1,go1.0
os.fspath
從Python3.6開始,有一個(gè)神奇的方法表示“轉(zhuǎn)換為文件系統(tǒng)路徑”。當(dāng)給定一個(gè)str或bytes時(shí),它返回輸入。
對(duì)于所有類型的對(duì)象,它尋找__fspath__方法并調(diào)用它。這允許傳遞的對(duì)象是“帶有元數(shù)據(jù)的文件名”。
像open()或stat這樣的普通函數(shù)仍然能夠使用它們,只要__fspath__返回正確的東西。
例如,這里有一個(gè)函數(shù)將一些數(shù)據(jù)寫入一個(gè)文件,然后檢查其大小。它還將文件名記錄到標(biāo)準(zhǔn)輸出,以便追蹤:
defwrite_and_test(filename):
print("writinginto",filename)
withopen(filename,"w")asfpout:
fpout.write("hello")
print("sizeof",filename,"is",os.path.getsize(filename))
你可以用你期望的方式來調(diào)用它,用一個(gè)字符串作為文件名:
write_and_test("plain.txt")
writingintoplain.txt
sizeofplain.txtis5
然而,可以定義一個(gè)新的類,為文件名的字符串表示法添加信息。這樣可以使日志記錄更加詳細(xì),而不改變?cè)瓉淼墓δ埽?/p>
classDocumentedFileName:
def__init__(self,fname,why):
self.fname=fname
self.why=why
def__fspath__(self):
returnself.fname
def__repr__(self):
returnf"DocumentedFileName(fname={self.fname!r},why={self.why!r})"
用DocumentedFileName實(shí)例作為輸入運(yùn)行該函數(shù),允許open和os.getsize函數(shù)繼續(xù)工作,同時(shí)增強(qiáng)日志:
write_and_test(DocumentedFileName("documented.txt","becauseit'sfun"))
writingintoDocumentedFileName(fname='documented.txt',why="becauseit'sfun")
sizeofDocumentedFileName(fname='documented.txt',why="becauseit'sfun")is5
以上內(nèi)容為大家介紹了Python3.6中針對(duì)文件系統(tǒng)的神奇方法,希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。http://www.parentadvocate.org/