From dc32d361ccde6c1fbc65d5723277cc0695c30cff Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Thu, 30 Apr 2009 12:47:12 -0400 Subject: [PATCH] typos --- special-method-names.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/special-method-names.html b/special-method-names.html index b19fa86..328b52a 100644 --- a/special-method-names.html +++ b/special-method-names.html @@ -212,7 +212,7 @@ __or__ >>> 1 / x Fraction(3, 1) -

This is not a case of taking a Fraction and dividing it by an integer (as in the previous example). That case was straightforward: x / 3 calls x.__truediv__(3), and the __truedive__() method of the Fraction class handles all the math. But integers don’t “know” how to do arithmetic operations with fractions. So why does this example work? +

This is not a case of taking a Fraction and dividing it by an integer (as in the previous example). That case was straightforward: x / 3 calls x.__truediv__(3), and the __truediv__() method of the Fraction class handles all the math. But integers don’t “know” how to do arithmetic operations with fractions. So why does this example work?

The answer lies in a second set of arithmetic special methods with reflected operands. Given an arithmetic operation that takes two operands (e.g. x / y), there are two ways to go about it: @@ -374,7 +374,7 @@ __ior__

  1. Try calling x.__itruediv__(y). If this method is defined and returns a value other than NotImplemented, we’re done.
  2. Try calling x.__truediv__(y). If this method is defined and returns a value other than NotImplemented, the old value of x is discarded and replaced with the return value, just as if you had done x = x / y instead. -
  3. Try calling y.__rtruediv__(y). If this method is defined and returns a value other than NotImplemented, the old value of x is discarded and replaced with the return value. +
  4. Try calling y.__rtruediv__(x). If this method is defined and returns a value other than NotImplemented, the old value of x is discarded and replaced with the return value.

So you only need to define in-place methods like the __itruediv__() method if you want to do some special optimization for in-place operands. Otherwise Python will essentially reformulate the in-place operand to use a regular operand + a variable assignment.