【发布时间】:2021-12-08 14:24:17
【问题描述】:
我正在编写一个 python 程序,它对组合电路执行一些操作,例如比较与其他电路的相等性、合并门、计数门、计数连接、查找扇出门......
现在我用以下方式表示组合电路:
(我还添加了平等测试)
class Circuit:
def __init__(self):
self.gates = {} # key = the gates number, value = the gate
def __eq__(self, other):
if set(self.gates.keys()) != set(other.gates.keys()):
return False
for key in self.gates.keys():
if self.gates[key] != other.gates[key]:
return False
return True
class Gate:
def __init__(self, gate_type, number):
self.gate_type = gate_type # and, or, nand, nor, xor, xnor
self.number = number
self.incoming_gates = []
self.outgoing_gates = []
def __eq__(self, other):
# i know this is not correct, but in my case correct enough
return (
self.gate_type == other.gate_type
and self.number == other.number
and len(self.incoming) == len(other.incoming)
and len(self.outgoing) == len(other.outgoing)
)
我在代码中的表示对我来说似乎很费力,所以我正在寻找一种更好的方法来做到这一点。我已经搜索了这方面的最佳做法,但没有找到任何东西。
【问题讨论】:
-
dataclasses(标准库)或attrs会在一定程度上帮助你。 -
@AKX 我明白为什么
dataclasses和attrs都有助于编写更少、更精确的代码,但它对表示有何帮助? -
你的表现很好。
dataclasses将有助于样板文件,但您表示数据的方式没有任何问题。你已经很好地掌握了如何使用类,在我看来是这样的