On 21 February 2013 23:41, Schizoid Man <schiz_...@21stcentury.com> wrote: > "Oscar Benjamin" <oscar.j.benja...@gmail.com> wrote in >> Then you want operator.pow: >> >>>>> import operator >>>>> operator.pow(3, 2) >> >> 9 >> >> math.pow is basically the (double)pow(double, double) function from >> the underlying C library. operator.pow(a, b) is precisely the same as >> a**b. > > So how is operator.pow() different from just pow()?
operator.pow(a, b) calls a.__pow__(b). This is also what a**b does. If a and b are ints then the __pow__ method will create the appropriate int exactly without overflow and return it. You can make your own class and give it a __pow__ function that does whatever you like: >>> class Number(object): ... def __pow__(self, other): ... print('__pow__ called, returning 3') ... return 3 ... >>> n = Number() >>> result = n**3 __pow__ called, returning 3 >>> result 3 operator.pow will call the method: >>> import operator >>> operator.pow(n, 3) __pow__ called, returning 3 3 math.pow will not: >>> import math >>> math.pow(n, 3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: a float is required The math module essentially exposes the functions that would be available in C after importing math.h. So when you call math.pow(a, b), a and b are if possible converted to float (which corresponds to a double in C) and then the result is computed and returned as a float. Oscar -- http://mail.python.org/mailman/listinfo/python-list