W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
這些類可以用作未定義類型。?Environment?的構(gòu)造函數(shù)接受一個(gè)可以是 那些類或一個(gè)Undefined?的自定義子類的?undefined?參數(shù)。無論何時(shí), 這些對象創(chuàng)建或返回時(shí),模板引擎都不能查出其名稱或訪問其屬性。未定義值上的 某些操作之后是允許的,而其它的會失敗。
最接近常規(guī) Python 行為的是?StrictUndefined?,如果它是一個(gè)未定義對象, 它不允許除了測試之外的一切操作。
The default undefined type. This undefined type can be printed and iterated over, but every other access will raise an?UndefinedError:
>>> foo = Undefined(name='foo')
>>> str(foo)
''
>>> not foo
True
>>> foo + 42
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
None?或給未定義對象的錯(cuò)誤消息 unicode 字符串。
None?或引起未定義對象創(chuàng)建的對象(例如一個(gè)屬性不存在)。
未定義變量/屬性的名稱,如果沒有此類信息,留為?None?。
未定義對象想要拋出的異常。這通常是?UndefinedError?或?SecurityError?之一。
_fail_with_undefined_error(args,?kwargs*)
參數(shù)任意,調(diào)用這個(gè)方法時(shí)會拋出帶有由未定義對象上存儲的未定義 hint 生成的錯(cuò)誤信息的?_undefined_exception?異常。
An undefined that returns the debug info when printed.
>>> foo = DebugUndefined(name='foo')
>>> str(foo)
'{{ foo }}'
>>> not foo
True
>>> foo + 42
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
An undefined that barks on print and iteration as well as boolean tests and all kinds of comparisons. In other words: you can do nothing with it except checking if it’s defined using the?defined?test.
>>> foo = StrictUndefined(name='foo')
>>> str(foo)
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
>>> not foo
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
>>> foo + 42
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
未定義對象由調(diào)用?undefined?創(chuàng)建。
實(shí)現(xiàn)
Undefined?對象通過重載特殊的?underscore?方法實(shí)現(xiàn)。例如 默認(rèn)的?Undefined?類實(shí)現(xiàn)?unicode?為返回一個(gè)空字符串,但?int?和其它會始終拋出異常。你可以自己通過返回?0?實(shí)現(xiàn)轉(zhuǎn)換為 int:
class NullUndefined(Undefined):
def __int__(self):
return 0
def __float__(self):
return 0.0
要禁用一個(gè)方法,重載它并拋出?_undefined_exception?。因 為這在未定義對象中非常常用,未定義對象有輔助方法?_fail_with_undefined_error()?自動(dòng)拋出錯(cuò)誤。這里的一個(gè)類 工作類似正規(guī)的?Undefined?,但它在迭代時(shí)阻塞:
class NonIterableUndefined(Undefined):
iter = Undefined._fail_with_undefined_error
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: