有人可以解释或参考用于将源解释为HAS-A关系中使用的函数中的参数的文档吗?
我正在尝试提高我对python中OOP的了解,并从https://runestone.academy/runestone/books/published/pythonds/Introduction/ObjectOrientedProgramminginPythonDefiningClasses.html#inheritance-logic-gates-and-circuits中学习。有一个类继承和组合用法的示例(1.13.2。继承:逻辑门和电路)。我无法理解“源”作为以下代码的函数参数的背景。我可以在调试模式下看到,整个类实例都作为参数发送。是“来源”保留字吗?在下面的代码中-class Connector HAS-A class LogicGate
和引用函数tgate.setNextPin(self)
,但在BinaryGate
类中存在def setNextPin(self,source)
,而我的问题出在源引用周围。
class LogicGate:
def __init__(self,n):
self.name = n
self.output = None
def getLabel(self):
return self.name
def getOutput(self):
self.output = self.performGateLogic()
return self.output
class BinaryGate(LogicGate):
def __init__(self,n):
super(BinaryGate, self).__init__(n)
self.pinA = None
self.pinB = None
def getPinA(self):
if self.pinA == None:
return int(input("Enter Pin A input for gate "+self.getLabel()+"-->"))
else:
return self.pinA.getFrom().getOutput()
def getPinB(self):
if self.pinB == None:
return int(input("Enter Pin B input for gate "+self.getLabel()+"-->"))
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 UnaryGate(LogicGate):
def __init__(self,n):
LogicGate.__init__(self,n)
self.pin = None
def getPin(self):
if self.pin == None:
return int(input("Enter Pin input for gate "+self.getLabel()+"-->"))
else:
return self.pin.getFrom().getOutput()
def setNextPin(self,source):
if self.pin == None:
self.pin = source
else:
print("Cannot Connect: NO EMPTY PINS on this gate")
class NotGate(UnaryGate):
def __init__(self,n):
UnaryGate.__init__(self,n)
def performGateLogic(self):
if self.getPin():
return 0
else:
return 1
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
def main():
g1 = AndGate("G1")
g2 = NotGate("G2")
c1 = Connector(g1,g2)
print(g2.getOutput())
main()
答案很简单:(Connector。init中的setNextPin引用Connector类作为参数。这就是我一直在寻找的来源。结案。