/ docs / conversion.rst
conversion.rst
 1  Conversion methods and gmpy2's numbers
 2  ======================================
 3  
 4  Conversion methods
 5  ------------------
 6  
 7  A python object could interact with gmpy2 if it implements one of the following methods:
 8  
 9  - **__mpz__** : return an object of <type 'mpz'>.
10  - **__mpq__** : return an object of <type 'mpq'>.
11  - **__mpfr__** : return an object of <type 'mpfr'>.
12  - **__mpc__** : return an object of <type 'mpc'>.
13  
14  | Implementing on of these methods allow gmpy2 to convert a python object into a gmpy2 type.
15  | Example::
16  
17      >>> from gmpy2 import mpz
18      >>> class CustInt:
19      ...     def __init__(self, x):
20      ...             self.x = x
21      ...     def __mpz__(self):
22      ...             return mpz(self.x)
23      ...
24      >>> ci = CustInt(5)
25      >>> z = mpz(ci); z
26      mpz(5)
27      >>> type(z)
28      <type 'mpz'>
29  
30  Arithmetic operations
31  ---------------------
32  
33  | gmpy2 allow arithmetic operations between gmpy2 numbers and objects with conversion methods.
34  | Operation with object that implements floating conversion and exact conversion methods are not supported.
35  | That means that only the following cases are supported:
36  
37  - An integer type have to implement **__mpz__**
38  - A rational type have to implement **__mpq__** and can implement **__mpz__**
39  - A real type have to implement **__mpfr__**
40  - A complex type have to implement **__mpc__** and can implement **__mpfr__**
41  
42  Examples::
43  
44      >>> from gmpy2 import mpz, mpq, mpfr, mpc
45      >>> class Q:
46      ...     def __mpz__(self): return mpz(1)
47      ...     def __mpq__(self): return mpq(3,2)
48      >>> q = Q()
49      >>> mpz(2) + q
50      mpq(7,2)
51      >>> mpq(1,2) * q
52      mpq(3,4)
53      >>> mpfr(10) * q
54      mpfr('15.0')