Commit 310babe8 authored by Martin Mareš's avatar Martin Mareš
Browse files

Výrazy: Dvě objektové verze

parent e7124f5b
......@@ -18,15 +18,12 @@ class NumNode(Node):
return self.value
class BinaryNode(Node):
class AddNode(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) + ')'
......@@ -34,7 +31,11 @@ class AddNode(BinaryNode):
return self.left.eval() + self.right.eval()
class SubNode(BinaryNode):
class SubNode(Node):
def __init__(self, left, right):
self.left = left
self.right = right
def __str__(self):
return '(' + str(self.left) + '-' + str(self.right) + ')'
......@@ -43,7 +44,11 @@ class SubNode(BinaryNode):
return self.left.eval() - self.right.eval()
class MulNode(BinaryNode):
class MulNode(Node):
def __init__(self, left, right):
self.left = left
self.right = right
def __str__(self):
return '(' + str(self.left) + '*' + str(self.right) + ')'
......@@ -52,7 +57,11 @@ class MulNode(BinaryNode):
return self.left.eval() * self.right.eval()
class DivNode(BinaryNode):
class DivNode(Node):
def __init__(self, left, right):
self.left = left
self.right = right
def __str__(self):
return '(' + str(self.left) + '/' + str(self.right) + ')'
......
#!/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
def __str__(self):
return '(' + str(self.left) + self.op_name + str(self.right) + ')'
class AddNode(BinaryNode):
op_name = '+'
def eval(self):
return self.left.eval() + self.right.eval()
class SubNode(BinaryNode):
op_name = '-'
def eval(self):
return self.left.eval() - self.right.eval()
class MulNode(BinaryNode):
op_name = '*'
def eval(self):
return self.left.eval() * self.right.eval()
class DivNode(BinaryNode):
op_name = '/'
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