How To capture an id into an array..
Peter Otten
__peter__ at web.de
Mon Mar 29 14:02:41 EST 2004
Balaji wrote:
> Suppose if some body wants to assign an e=E() to an expression class..
> he may define then e=v+v1(where v and v1 both belong to a variable class)
> now again if we define say v2=V() and then try to multiply v2 with e then
> I want to raise an error that it is a nonlinear term..
>
> So what I though was if i keep track of all the instances id then I might
> raise an exception...
>
> But the problem was i couldnt check the right side of an assigment...
I'm not sure what you mean - my guess is entirely different from Christan's
- but anyway:
I suppose you want an expression
a operator b
to either raise an exception or return a new expression and base this
decision on both the kind of a and b. You can do this by providing a lookup
table with all allowed operations (or all forbidden ops, if that is
significantly smaller). Here's the simplest implementation I could think
of:
<expr.py>
import sets
supported = sets.Set([
# operation, leftoperand, rightoperand
("+","v", "v"),
("+","+", "v"),
("+","v", "+"),
("+","+", "+"),
("*","v", "v"),
# complete with all allowed
# combinations of operators/values
])
class Base:
"""Shared implementation for Expressions and Values """
def op(self, operator, other):
if (operator, self.operator, other.operator) in supported:
return Expression(operator, self, other)
else:
raise ValueError("unsupported operation")
def __add__(self, other):
return self.op("+", other)
def __mul__(self, other):
return self.op("*", other)
# add __div__ etc. here
class Expression(Base):
def __init__(self, operator, left, right):
self.operator = operator
self.left = left
self.right = right
def __str__(self):
return str(self.left) + self.operator + str(self.right)
class Value(Base):
operator = "v"
def __init__(self, value):
self.value = value
def __str__(self):
return "Value(%s)" % self.value
if __name__ == "__main__":
print Value(3) * Value(4)
print Value(1) + Value(2) + Value(3)
print Value(1) + Value(2) * Value(3) # will raise an exception
</expr.py>
Peter
More information about the Python-list
mailing list