理解python代码以实现逻辑表达式
我想在python中的((A/\B)/C)等逻辑表达式上存储和使用(从表达式中访问每个文本,并进一步访问)。我找到了一个办法。我把代码贴在下面。但作为一个初学者,我无法理解它。有人能给我解释一下这段代码是如何工作的,并给出所需的输出吗。请原谅我的任何错误,因为这是我第一次在stackoverflow上理解python代码以实现逻辑表达式,python,logic,logical-operators,Python,Logic,Logical Operators,我想在python中的((A/\B)/C)等逻辑表达式上存储和使用(从表达式中访问每个文本,并进一步访问)。我找到了一个办法。我把代码贴在下面。但作为一个初学者,我无法理解它。有人能给我解释一下这段代码是如何工作的,并给出所需的输出吗。请原谅我的任何错误,因为这是我第一次在stackoverflow上 class Element(object): def __init__(self, elt_id, elt_description=None): self.id = el
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)
它通过设置类
元素
并定义位运算符&
|
~
返回所请求操作的字符串表示形式
通常,~a
是对整数的逐位运算:它将所有0
位更改为1
,反之亦然。但是,由于运算符\uuuu invert\uuuu
已被重新定义,因此执行此操作时
a = Element("A")
print(~a)
而不是像处理整数那样获取a
的位逆,而是获取字符串“~a”
它非常聪明,但我怀疑它对你想做的事情不会很有用。它所做的只是将表达式转换为字符串