在Day25-CaseInsensitiveDict出現了很多被雙底線包圍的方法,這些特別的方法可以針對語言層級的運算子定義並客製化自己的行為,舉例來說,CaseInsensitiveDict定義了__getitem__()方法,若x為CaseInsensitiveDict的物件,亦即重新定義了x[key]
所產生的行為
This is Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators
__new__和__init__須互相配合才能創造並初始化一個物件,較常使用的應該是__init__
Use __new__ when you need to control the creation of a new instance.
Use __init__ when you need to control initialization of a new instance.
相較於物件的生成,物件的回收需透過__del__,常被稱為finalizer
或是destructor
題外話,del x
和x.__del__()
在行為上有些差異
del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x’s reference count reaches zero.
repr()
built-in functionofficial
string representation of an objectstr(object)
and the built-in functions format()
and print()
informal
or nicely printable string representation of an objectformat()
built-in function, and by extension, evaluation of formatted string literals and the str.format()
methodformatted
string representation of an object至少需要實現__repr__
在model.py中PreparedRequest定義如下
def __repr__(self):
return '<PreparedRequest [%s]>' % (self.method)
called
as a functionContainers usually are sequences (such as lists or tuples) or mappings (like dictionaries), but can represent other containers as well
A context manager is an object that defines the runtime context to be established when executing a
with
statement.
The context manager handles theentry into
, and theexit from
, the desired runtime context for the execution of the block of code.