Mapytex/mapytex/calculus/API/tokens/number.py

131 lines
3.0 KiB
Python
Raw Normal View History

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 lafrite <lafrite@Poivre>
#
# Distributed under terms of the MIT license.
"""
Tokens representing interger and decimal
"""
from .token import Token
from ...core.MO import MO, MOnumber
from ...core.MO.fraction import MOFraction
from decimal import Decimal as _Decimal
__all__ = ["Integer", "Decimal"]
class Integer(Token):
""" Token representing a integer
:example:
>>> Integer(4)
<Integer 4>
>>> a = MOnumber(4)
>>> Integer.from_mo(a)
<Integer 4>
"""
def __init__(self, a, name="", ancestor=None):
if not isinstance(a, MO):
if not isinstance(a, int):
raise TypeError
mo = MOnumber(a)
else:
mo = a
Token.__init__(self, mo, name, ancestor)
self._mathtype = 'entier'
@classmethod
def from_mo(cls, mo, name="", ancestor=None):
if not isinstance(mo, MOnumber):
raise TypeError
if not isinstance(mo.value, int):
raise TypeError
return cls(mo, name, ancestor)
@classmethod
def random(cls):
raise NotImplemented
class Decimal(Token):
""" Token representing a decimal """
def __init__(self, a, name="", ancestor=None):
if not isinstance(a, MO):
if isinstance(a, (str, float)):
mo = MOnumber(Decimal(a))
else:
raise TypeError
else:
mo = a
self._mathtype = 'décimal'
Token.__init__(self, mo, name, ancestor)
@classmethod
def from_mo(cls, mo, name="", ancestor=None):
if not isinstance(mo, MOnumber):
raise TypeError
if not isinstance(mo.value, _Decimal):
raise TypeError
return cls(mo, name, ancestor)
@classmethod
def random(cls):
raise NotImplemented
class Fraction(Token):
""" Token representing a fraction """
def __init__(self, a, name="", ancestor=None):
if not isinstance(a, MO):
if isinstance(a, str):
num, denom = a.split('/')
2018-12-13 12:45:39 +00:00
mo = MOFraction(int(num), int(denom))
else:
raise TypeError
else:
mo = a
self._mathtype = 'fraction'
Token.__init__(self, mo, name, ancestor)
@classmethod
def from_mo(cls, mo, name="", ancestor=None):
if not isinstance(mo, MOFraction):
raise TypeError
if not isinstance(mo._numerator, MOnumber):
raise TypeError
if not isinstance(mo._denominator, MOnumber):
raise TypeError
return cls(mo, name, ancestor)
@classmethod
def random(cls):
raise NotImplemented
@property
def numerator(self):
return self._mo.numerator
@property
def denominator(self):
return self._mo.denominator
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del