W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
這些類可以用作未定義類型。?Environment?的構(gòu)造函數(shù)接受一個可以是 那些類或一個Undefined?的自定義子類的?undefined?參數(shù)。無論何時, 這些對象創(chuàng)建或返回時,模板引擎都不能查出其名稱或訪問其屬性。未定義值上的 某些操作之后是允許的,而其它的會失敗。
最接近常規(guī) Python 行為的是?StrictUndefined?,如果它是一個未定義對象, 它不允許除了測試之外的一切操作。
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?或給未定義對象的錯誤消息 unicode 字符串。
None?或引起未定義對象創(chuàng)建的對象(例如一個屬性不存在)。
未定義變量/屬性的名稱,如果沒有此類信息,留為?None?。
未定義對象想要拋出的異常。這通常是?UndefinedError?或?SecurityError?之一。
_fail_with_undefined_error(args,?kwargs*)
參數(shù)任意,調(diào)用這個方法時會拋出帶有由未定義對象上存儲的未定義 hint 生成的錯誤信息的?_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)建。
實現(xiàn)
Undefined?對象通過重載特殊的?underscore?方法實現(xiàn)。例如 默認的?Undefined?類實現(xiàn)?unicode?為返回一個空字符串,但?int?和其它會始終拋出異常。你可以自己通過返回?0?實現(xiàn)轉(zhuǎn)換為 int:
class NullUndefined(Undefined):
def __int__(self):
return 0
def __float__(self):
return 0.0
要禁用一個方法,重載它并拋出?_undefined_exception?。因 為這在未定義對象中非常常用,未定義對象有輔助方法?_fail_with_undefined_error()?自動拋出錯誤。這里的一個類 工作類似正規(guī)的?Undefined?,但它在迭代時阻塞:
class NonIterableUndefined(Undefined):
iter = Undefined._fail_with_undefined_error
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: