[英]Explanation of a function definition in logic gate code in Problems in Data Structures and Algorithms
(我是Python和OOP的新手,所以請隨時告知我是否使用荒謬的語言。)
《 數據結構和算法中的問題 》一書以分層方式實現了二進制和一元邏輯門的代碼。 請參閱我的問題的底部以獲取完整的相關代碼。
我的特定查詢是:在Connector類的構造函數中,有一行
tgate.setNextPin(self)
回到定義setNextPin函數的一元門:
def setNextPin(self,source):
if self.pin == None:
self.pin = source
else:
print("Cannot Connect: NO EMPTY PINS on this gate")
函數setNextPin中的“源”是函數setNextPin的輸入。 因此,當我看到行tgate.setNextPin(self)時,它告訴我返回到一元類(tgate)以查找函數setNextPin,並且setNextPin函數的輸入(“源”)是self,在這種情況是Connector類的實例。 但是,我真的不明白這有什么道理。 我看不到連接器類如何成為setNextPin中變量“ source”的輸入。
完整代碼:
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 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.getName()+"-->"))
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
Connector
類表示用於將邏輯門相互連接的導線。 setNextPin()
被賦予一個Connector
,並將其與pin
屬性關聯。 當它想要獲取提供其輸入的邏輯門時,會調用self.pin.getFrom()
,該方法轉到Connector
getFrom()
方法,該方法然后返回Connector
的fromgate
屬性,該屬性將是導線的另一端。
首先,我們應該注意setNextPin(self,source)
也是binaryGate
類和unaryGate
。
在函數定義setNextPin(self,source)
, self
是tgate(alias of a Gate class)
, source
是Connector類的實例。 假設aaa-->bbb
( a
連接到b
),則連接器將成為對象bbb的PIN和連接器屬性的別名。 fromGate
將是先前鏈接的別名aaa
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.