object.__div__(self, other)
object.__truediv__(self, other)
The division operator (/) is implemented by these methods. The
__truediv__() method is used when __future__.division is in effect, otherwise __div__() is used. If only one of these two methods is
defined, the object will not support division in the alternate
context; TypeError will be raised instead.A future statement is a directive to the compiler that a particular
[python program] should be compiled using syntax or semantics that will be
available in a ... future release of Python. The future
statement is intended to ease migration to future versions of Python
that introduce incompatible changes to the language. It allows use of
the new features before the release in which the
feature becomes standard.future_statement: from __future__ import feature
The features recognized by Python 2.x are unicode_literals,
print_function, absolute_import, division, generators, nested_scopes
and with_statement
现在,一些测试:~$ python2.7
Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 3/2
1
>>> exit()
~$ python3.2
Python 3.2.3 (v3.2.3:3d0686d90f55, Apr 10 2012, 11:25:50)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 3/2
1.5
因此,您可以看到,python 3.x中的/操作符的效果发生了变化class Dog(object):
def __div__(self, other):
print("__div__ called")
def __truediv__(self, other):
print("__truediv__ called")
Dog() / Dog()
--output:--
~/python_programs$ python2.7 myprog.py
__div__ called
~/python_programs$ python3.4 myprog.py
__truediv__ called
因为在python 2.x中,__truediv__不是由/运算符调用的,所以在python2.x中重写__truediv__没有效果。PEP 238 - PEP 238 -- Changing the Division Operator
We propose the following transitional measures:
- Classic division will remain the default in the Python 2.x
series; true division will be standard in Python 3.0.
- The // operator will be available to request floor[, i.e. integer,]
division unambiguously.
- The future division statement, spelled "from __future__ import
division", will change the / operator to mean true division
throughout the [program]
现在,看看这里发生了什么:from __future__ import division
class Dog(object):
def __div__(self, other):
print("__div__ called")
def __truediv__(self, other):
print("__truediv__ called")
Dog() / Dog()
--output:--
~/python_programs$ python2.7 myprog.py
__truediv__ called
~/python_programs$ python3.4 myprog.py
__truediv__ called
现在,您可以获得python 2.x中的/操作符的python3.x效果。因此,现在可以重写__truediv__,以使/操作符按您的要求工作。
注意,如果您想在python 3.x中使用整数除法,即3/2 => 1,那么必须使用//运算符,该运算符由__floordiv__实现。同样,如果在python 2.x中执行from __future__ import division,那么要获得整数除法,必须使用//运算符;如果要重写类中的//运算符,则需要实现__floordiv__。