Python 类中的 magic method

Author: yifei / Created: June 22, 2018, 4:55 p.m. / Modified: June 22, 2018, 4:56 p.m. / Edit

string representation

define __str__ and __repr__ method, note that __str__ is meant to be read by human, while eval(repr(x)) == x should always be true


define __format__ "hello {:param}".fromat(x) is called as x.__format__("param")

context manager protocol

__enter__(self) -> object
__exit__(self, exception_type, exception_val, trace_back) -> bool

if __exit__ returns True, it means the exception has been handled

有任何问题可以发邮件到 kongyifei (at) 讨论