3.3.8 强制规则: Coercion rules

This section used to document the rules for coercion. As the language has evolved, the coercion rules have become hard to document precisely; documenting what one version of one particular implementation does is undesirable. Instead, here are some informal guidelines regarding coercion. In Python 3.0, coercion will not be supported.

0. 如果x是串对象,并且op是取模运算符(

1. 如果x是一个类实例:

1a. 如果x有__coerce__()方法:就用x.__coerce__(y)返回的二元组的值替换x和y. 如果它返回None则跳过步骤2.

1b. 如果x或y在强制转换后都不是类实例了, 转到步骤3.

1c. 如果x有方法__op__(), 返回x.__op__(y);否则恢复步骤1a之前的x和y的值.

2.

2a. 如果y有__coerce__()方法:就用y.__coerce__(x)返回的二元组的值替换y和x. 如果它返回None则跳过步骤2.

2b. 如果x或y在强制转换后都不是类实例了, 转到步骤3.

2b. 如果y有方法__rop__(), 返回y.__rop__(x);否则恢复步骤2a之前的x和y的值.

3. 仅仅在x和y都不是类实例时, 才会执行到这一步.

3a. 如果op为+并且x是一个有序类型, 那么就执行有序类型的连接操作.

3b. 如果op为*并且一个操作数为有序类型, 另一个是整数, 就执行有序类型重复操作.

3c. 否则, 两个操作数必须是数值型的; 它们尽可能地强制转换成通用类型, 并且为该类型调用数值运算符.