Commit e7124f5b authored by Martin Mareš's avatar Martin Mareš
Browse files

Výrazy: Ještě objektová verze s dědičností

parent 2289c465
#!/usr/bin/python3
class Node:
def eval(self):
raise NotImplemented()
class NumNode(Node):
def __init__(self, x):
self.value = x
def __str__(self):
return str(self.value)
def eval(self):
return self.value
class BinaryNode(Node):
def __init__(self, left, right):
self.left = left
self.right = right
class AddNode(BinaryNode):
def __str__(self):
return '(' + str(self.left) + '+' + str(self.right) + ')'
def eval(self):
return self.left.eval() + self.right.eval()
class SubNode(BinaryNode):
def __str__(self):
return '(' + str(self.left) + '-' + str(self.right) + ')'
def eval(self):
return self.left.eval() - self.right.eval()
class MulNode(BinaryNode):
def __str__(self):
return '(' + str(self.left) + '*' + str(self.right) + ')'
def eval(self):
return self.left.eval() * self.right.eval()
class DivNode(BinaryNode):
def __str__(self):
return '(' + str(self.left) + '/' + str(self.right) + ')'
def eval(self):
return self.left.eval() // self.right.eval()
x = AddNode(MulNode(NumNode(3), NumNode(4)), SubNode(NumNode(5), NumNode(6)))
print(x)
print(x.eval())
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment