我正在研究this book,并试图扩展其代码以使其成为半加法器,最终成为全加法器。
我认为我应该实现一种从半加法器分别返回进位和进位的方法,以便于连接到后面的门。但是,这就是我要消隐的地方。我还需要某种方法来调用performGateLogic
上的HalfAdder
并将“ XorGate
和AndGate
的输入“管道”化,并尝试使用Connector
。我的大脑只是束缚在这里的方法调用和类关系的椒盐脆饼中,我很感谢有人将其弄清楚。
class LogicGate:
def __init__(self,n):
self.name = n
self.output = None
def getName(self):
return self.name
def getOutput(self):
self.output = self.performGateLogic()
return self.output
class BinaryGate(LogicGate):
def __init__(self,n):
LogicGate.__init__(self,n)
self.pinA = None
self.pinB = None
def getPinA(self):
if self.pinA == None:
return int(input("Enter Pin A input for gate "+self.getName()+"-->"))
else:
return self.pinA.getFrom().getOutput()
def getPinB(self):
if self.pinB == None:
return int(input("Enter Pin B input for gate "+self.getName()+"-->"))
else:
return self.pinB.getFrom().getOutput()
def setNextPin(self,source):
if self.pinA == None:
self.pinA = source
else:
if self.pinB == None:
self.pinB = source
else:
print("Cannot Connect: NO EMPTY PINS on this gate")
class AndGate(BinaryGate):
def __init__(self,n):
BinaryGate.__init__(self,n)
def performGateLogic(self):
a = self.getPinA()
b = self.getPinB()
if a==1 and b==1:
return 1
else:
return 0
class XorGate(BinaryGate):
def __init__(self,n):
BinaryGate.__init__(self,n)
def performGateLogic(self):
a = self.getPinA()
b = self.getPinB()
if (a ==1 and b==0) or (a==0 and b==1):
return 1
else:
return 0
class Connector:
def __init__(self, fgate, tgate):
self.fromgate = fgate
self.togate = tgate
tgate.setNextPin(self)
def getFrom(self):
return self.fromgate
def getTo(self):
return self.togate
class HalfAdder(BinaryGate):
def __init__(self,n):
BinaryGate.__init__(self,n)
self.bits, self.carry = None, None
self.a, self.b = None, None
self.xor = XorGate('XO')
self.and_ = AndGate('A')
self.c1 = Connector(self.xor.getPinA(), self.and_.getPinA())
self.c2 = Connector(self.xor.getPinB(), self.and_.getPinB())
def performGateLogic(self):
self.a = self.getPinA()
self.b = self.getPinB()
self.bits = 1 if (self.a ==1 and self.b==0) or (self.a==0 and self.b==1) else 0
self.carry = 1 if (self.a==1 and self.b ==1) else 0
return self.bits + self.carry
运行print(HalfAdder('HA').getOutput())
会产生
File "./circuits.py", line 178, in __init__
self.c1 = Connector(self.xor.getPinA(), self.and_.getPinA())
File "./circuits.py", line 161, in __init__
tgate.setNextPin(self)
AttributeError: 'int' object has no attribute 'setNextPin'
某些内容已设置为int
,但在哪里找不到。