【发布时间】:2017-06-12 20:38:52
【问题描述】:
我想在 python 中存储和工作(从表达式中访问每个文字,并进一步访问)像 ((A /\ B) / C) 这样的逻辑表达式。我找到了一种方法。我在下面发布代码。但作为一个初学者,我无法理解它。谁能向我解释这段代码是如何工作的并给出所需的输出。请原谅我第一次在 stackoverflow 上出现的任何错误。
class Element(object):
def __init__(self, elt_id, elt_description=None):
self.id = elt_id
self.description = elt_description
if self.description is None:
self.description = self.id
def __or__(self, elt):
return CombinedElement(self, elt, op="OR")
def __and__(self, elt):
return CombinedElement(self, elt, op="AND")
def __invert__(self):
return CombinedElement(self, op="NOT")
def __str__(self):
return self.id
class CombinedElement(Element):
def __init__(self, elt1, elt2=None, op="NOT"):
# ID1
id1 = elt1.id
if isinstance(elt1, CombinedElement):
id1 = '('+id1+')'
# ID2
if elt2 is not None:
id2 = elt2.id
if isinstance(elt2, CombinedElement):
id2 = '('+id2+')'
# ELT_ID
if op == "NOT" and elt2 is None:
elt_id = "~"+id1
elif op == "OR":
elt_id = id1+" v "+id2
elif op == "AND":
elt_id = id1+" ^ "+id2
# SUPER
super(CombinedElement, self).__init__(elt_id)
a = Element("A")
b = Element("B")
c = Element("C")
d = Element("D")
e = Element("E")
print(a&b|~(c&d)|~e)
Output :
((A ^ B) v (~(C ^ D))) v (~E)
【问题讨论】:
标签: python logic logical-operators