3.3 特殊方法名 Special method names

A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names.This is Python's approach to operator overloading, allowing classes to define their own behavior with respect to language operators. For instance, if a class defines a method named __getitem__(), and x is an instance of this class, then x[i] is equivalent to x.__getitem__(i). Except where mentioned, attempts to execute an operation raise an exception when no appropriate method is defined.

一个类可以实现以特殊句法才调用的某些操作(例如算术运算,下标操作及片断操作), 这是通过以特殊名字定义方法来实现的. 例如, 如果一个类定义了的方法名为__getitem__(), 并且x是这个类的实例, 那么x[i]就等价于x.__getitem__(i), (反过来是不正确的 -- 如果x是一个列表对象, x.__getitem__(i)不等价于x[i].)除了所提及的地方,试图执行没有适当的方法定义的操作会引起一个异常的抛出.

When implementing a class that emulates any built-in type, it is important that the emulation only be implemented to the degree that it makes sense for the object being modelled. For example, some sequences may work well with retrieval of individual elements, but extracting a slice may not make sense. (One example of this is the NodeList interface in the W3C's Document Object Model.)

当实现一个模拟任何内建类型的类时, 重要的地方在于模拟的程度只要使对象模拟时有效就行了. 例如, 某些有序类型的对象可能在单独提取某引起值时有效, 但在使用片断时是没有意义的.(这样的一个例子是在W3C的文档对象模型中的NodeList接口.)



子节目录