Mapytex/pymath/calculus/operator/operator_set.py

115 lines
3.0 KiB
Python
Raw Normal View History

#!/usr/bin/env python
# encoding: utf-8
import types
from .add import Add
from .div import Div
from .mul import Mul
from .par import Par
from .pw import Pw
from .sub import Sub
from .sub1 import Sub1
2016-02-27 08:40:29 +00:00
from .operator import Operator
class Operator_set(object):
""" Class for sets of operators"""
def __init__(self):
""" Initiate the operator_set """
self._operators = {}
def get_op(self, op, arity = 2):
2016-02-27 08:40:29 +00:00
r"""Return the corresponding operator
:op: symbole of the op
2016-02-27 08:40:29 +00:00
:arity: the arity (default is 2)
>>> op = Operator_set()
2016-02-27 08:40:29 +00:00
>>> op.store_operator(Add())
>>> op.get_op('+')
2016-02-27 08:40:29 +00:00
+
>>> mul = op.get_op('*')
Traceback (most recent call last):
...
KeyError: '* (arity: 2) is not available'
>>> op.store_operator(Mul())
>>> mul = op.get_op('*')
>>> mul.tex
2016-02-27 08:40:29 +00:00
'{op1} \\times {op2}'
>>> mul.txt
'{op1} * {op2}'
2016-02-27 08:40:29 +00:00
>>> op.store_operator(Sub1())
>>> sub1 = op.get_op('-')
Traceback (most recent call last):
...
KeyError: '- (arity: 2) is not available'
>>> sub1 = op.get_op('-', 1)
>>> sub1.tex
'- {op1}'
"""
try:
return getattr(self, self._operators[(op, arity)])
except KeyError:
raise KeyError("{theOp} (arity: {arity}) is not available".format(theOp = op, arity = arity))
def can_be_operator(cls, symbole):
2016-02-27 08:40:29 +00:00
r"""
Tell if the symbole can be an operator
>>> op = Operator_set()
>>> op.can_be_operator("+")
False
>>> op.store_operator(Add())
>>> op.can_be_operator("+")
True
"""
if type(symbole) == str:
return symbole in [i[0] for i in cls._operators]
else:
return False
def store_operator(self, operator):
""" Save the operator as a method and
:param operator: the operator (the class) (it will be accessible through .name method name.
2016-02-27 08:40:29 +00:00
>>> op = Operator_set()
>>> op._operators
{}
>>> op.store_operator(Add())
>>> op._operators
{('+', 2): 'add'}
>>> a = op.add
>>> a
+
>>> a.tex
'{op1} + {op2}'
2016-02-27 08:40:29 +00:00
>>> op.store_operator("+")
Traceback (most recent call last):
...
ValueError: + is not en Operator it's a <class 'str'>
"""
2016-02-27 08:40:29 +00:00
if isinstance(operator, Operator):
self._operators[operator.uniq_desc()] = operator.name
setattr(self, operator.name, operator)
else:
raise ValueError("{} is not en Operator it's a {}".format(operator, type(operator)))
op = Operator_set()
op.store_operator(Add())
op.store_operator(Div())
op.store_operator(Mul())
op.store_operator(Par())
op.store_operator(Pw())
op.store_operator(Sub())
op.store_operator(Sub1())
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del