此代码无法运行。它在运行(门)功能期间失败。我得到的第一个错误来自.__name__
电话。这不是我的主要问题,所以我并不特别担心这个错误
我得到的第二个错误是在最后一行(gate)中。错误消息显示gate不可调用。
我相信我的实际问题在于程序的结构。我是否误解(或误用)某些面向对象的原则?如果有人可以为我的代码提供示例或更正以获得更好的结构化方法,我将不胜感激。谢谢!
main.py
import builtins
import logic
print("Select a logic gate:")
print("1) AND")
print("2) NAND")
print("3) OR")
print("4) NOR")
print("Q) Quit Program")
logicGate = input()
if(int(logicGate) == 1):
run(logic.andGate)
elif(int(logicGate) == 2):
run(logic.nandGate)
elif(int(logicGate) == 3):
run(logic.orGate)
elif(int(logicGate) == 4):
run(logic.norGate)
elif(logicGate.lower() == 'q'):
prog = 'n'
else:
print("Invalid input. Please try again")
def toBool(s):
if s == 'True':
return True
elif s == 'False':
return False
else:
raise ValueError
def run(gate):
print(gate.__name__ + " Gate function")
print("Enter value for 'a'")
valA = input()
print("Enter value for 'b'")
valB = input()
print("Result: " + str(gate(toBool(valA), toBool(valB))))
和logic.py
def andGate(a, b):
if(a and b):
return True
else:
return False
def nandGate(a,b):
if(a and b):
return False
else:
return True
def orGate(a, b):
if(a or b):
return True
else:
return False
def norGate(a, b):
if(a or b):
return False
else:
return True
答案 0 :(得分:0)
在导入下移动你的defs并删除else:raise ....等ect部分......没有正确使用。
import builtins
import logic
def toBool(s):
if s == 'True':
return True
elif s == 'False':
return False
def run(gate):
print(gate.__name__ + " Gate function")
print("Enter value for 'a'")
valA = input()
print("Enter value for 'b'")
valB = input()
print("Result: " + str(gate(toBool(valA), toBool(valB))))
print("Select a logic gate:")
print("1) AND")
print("2) NAND")
print("3) OR")
print("4) NOR")
print("Q) Quit Program")
logicGate = input()
if(int(logicGate) == 1):
run(logic.andGate)
elif(int(logicGate) == 2):
run(logic.nandGate)
elif(int(logicGate) == 3):
run(logic.orGate)
elif(int(logicGate) == 4):
run(logic.norGate)
elif(logicGate.lower() == 'q'):
prog = 'n'
else:
print("Invalid input. Please try again")