Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Something like this?</p> <pre><code>import operator MAKE_BINARY = lambda opfn : lambda self,other : BinaryOp(self, asMagicNumber(other), opfn) MAKE_RBINARY = lambda opfn : lambda self,other : BinaryOp(asMagicNumber(other), self, opfn) class MagicNumber(object): __add__ = MAKE_BINARY(operator.add) __sub__ = MAKE_BINARY(operator.sub) __mul__ = MAKE_BINARY(operator.mul) __div__ = MAKE_BINARY(operator.div) __radd__ = MAKE_RBINARY(operator.add) __rsub__ = MAKE_RBINARY(operator.sub) __rmul__ = MAKE_RBINARY(operator.mul) __rdiv__ = MAKE_RBINARY(operator.div) def __neg__(self, other): return UnaryOp(self, lambda x : -x) @property def value(self): return self.eval() class Constant(MagicNumber): def __init__(self, value): self.value_ = value def eval(self): return self.value_ class Parameter(Constant): def __init__(self): super(Parameter, self).__init__(0.0) def setValue(self, v): self.value_ = v value = property(fset=setValue, fget=lambda self: self.value_) class BinaryOp(MagicNumber): def __init__(self, op1, op2, operation): self.op1 = op1 self.op2 = op2 self.opn = operation def eval(self): return self.opn(self.op1.eval(), self.op2.eval()) class UnaryOp(MagicNumber): def __init__(self, op1, operation): self.op1 = op1 self.operation = operation def eval(self): return self.opn(self.op1.eval()) asMagicNumber = lambda x : x if isinstance(x, MagicNumber) else Constant(x) </code></pre> <p>And here it is in action:</p> <pre><code>x = Parameter() y = 2*x*x + 3*x - x/2 x.value = 10 print y.value # prints 225 x.value = 20 print y.value # prints 850 # compute a series of x-y values for the function print [(x.value, y.value) for x.value in range(5)] # prints [(0, 0), (1, 5), (2, 13), (3, 26), (4, 42)] </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload