简体   繁体   English

如何组织代码/何时使用类?

[英]how to organize code / when to use classes?

The goal is to create a program which will effectively let the user create boolean logic statements (not started ), store those expressions, access them (expression_menu), build them (setup_table) and then evaluate them (truth) then finally test them (in another module). 目标是创建一个程序,该程序将有效地使用户创建布尔逻辑语句(未启动),存储这些表达式,访问它们(expression_menu),构建它们(setup_table),然后对其求值(真实)并最终对其进行测试(在另一个模块)。

Given all that, which is a fairly large project for my skills. 考虑到所有这些,这对我的技能来说是一个相当大的项目。 I'm stuck on how to organize everything. 我坚持如何组织一切。 I feel like i might want to be moving towards using classes because it might be easier to keep track of attributes... 我感觉我可能想转向使用类,因为跟踪属性可能更容易...

Immediately however my problem is that how to transfer around the boolean logic statements, obviously on line 29 i'll get a syntax error because x is undefined (the snippet of code only makes sense in lines 11 through 15. 但是,立即出现的问题是,如何在布尔逻辑语句之间进行传递,显然在第29行上,我会遇到语法错误,因为x是未定义的(代码段仅在第11到15行才有意义。

How can i organize my code here to better suit my goal 我如何在这里组织我的代码以更好地实现我的目标

def setup_table(variables=2):
    return (list(itertools.product(range(2), repeat = variables)))

def truth(variables=None,expression=None):
    truth_table = []
    for x in setup_table(variables):
        if expression:
            x.append(1)
        else:
            x.append(0)
        truth_table.append(x)
    return truth_table

def expression_menu():
    expression = input('''
    choose your expression:
    1. if ((p and q) or (p or q)) and not(r or not q):
    2. if (p or r) or (q and s):
    3. if (p or r) and ( q or (p and s))

    Expression: ''')
    table = None
    if int(expression) == 1:
        table = truth(variables = 3, expression =((x[0] and x[1]) or (x[0] or x[1])) and not (x[
    print(table)

if __name__ == "__main__":
    import itertools
    expression_menu()

You could make your boolean expression into a function. 您可以将布尔表达式转换为函数。

So: 所以:

table = truth(variables = 3, expression = lambda x: (x[0] and x[1]))

or: 要么:

def expression(x):
    return x[0] and x[1]
table = truth(variables = 3, expression = expression)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM