第670页 | Learning Python | 阅读 ‧ 电子书库

同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库

Test Your Knowledge: Answers

 

 
Classes can support iteration by defining (or inheriting) __getitem__ or __iter__. In all iteration contexts, Python tries to use __iter__ (which returns an object that supports the iteration protocol with a __next__ method) first: if no __iter__ is found by inheritance search, Python falls back on the __getitem__ indexing method (which is called repeatedly, with successively higher indexes).The __str__ and __repr__ methods implement object print displays. The former is called by the print and str built-in functions; the latter is called by print and str if there is no __str__, and always by the repr built-in, interactive echoes, and nested appearances. That is, __repr__ is used everywhere, except by print and str when a __str__ is defined. A __str__ is usually used for user-friendly displays; __repr__ gives extra details or the object’s as-code form.Slicing is caught by the __getitem__ indexing method: it is called with a slice object, instead of a simple index. In Python 2.6, __getslice__ (defunct in 3.0) may be used as well.In-place addition tries __iadd__ first, and __add__ with an assignment second. The same pattern holds true for all binary operators. The __radd__ method is also available for right-side addition.When a class naturally matches, or needs to emulate, a built-in type’s interfaces. For example, collections might imitate sequence or mapping interfaces. You generally shouldn’t implement expression operators if they don’t naturally map to your objects, though—use normally named methods instead.

请支持我们,让我们可以支付服务器费用。
使用微信支付打赏


上一页 · 目录下一页


下载 · 书页 · 阅读 ‧ 电子书库