逻辑门类执行流在这里究竟是如何工作的?

2024-10-03 09:12:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个LogicGate类,它可以有一个或两个输入行(分别是UnaryGateBinaryGate子类)和一个Connector类,它包含两个LogicGate对象,并且有一个方法将一个门的输出返回给另一个门,这样接收端的门就可以对它执行操作。我很难理解的是什么对象实际上在执行这里的get_from()方法:

class LogicGate:

    def __init__(self,n):
        self.label = n
        self.output = None

    def get_label(self):
        return self.label

    def get_output(self):
        self.output = self.perform_gate_logic()
        return self.output

class UnaryGate(LogicGate):

    def __init__(self,n):
        LogicGate.__init__(self,n)

        self.pin = None

    def get_pin(self):
        if self.pin == None:
            pin = int(input("Enter Pin input for gate " + self.get_label() + "-->"))
            while pin != 1 and pin != 0:
                pin = int(input("Try again with 1 or 0 -->"))
            return pin
        else:
            return self.pin.get_from().get_output()

    def set_next_pin(self,source):
        if self.pin == None:
            self.pin = source
        else:
            raise RuntimeError("ERROR: NO EMPTY PINS")

class Connector:

    def __init__(self,fgate,tgate):
        self.fromgate = fgate
        self.togate = tgate

        tgate.set_next_pin(self)

    def get_from(self):
        return self.fromgate

    def get_to(self):
        return self.togate

get_pin()方法中,到底在做什么?如果执行UnaryGateget_pin()Connectortogate,则get_from()返回相应的fromgate,后者依次执行get_output(),并基于从其连接的一个或两个门接收的输入返回10。我不能把我的头绕过去的是self.pin.get_from()部分。get_from()是否在pin对象上被调用,据我所知,它只是一个类属性,可以是10None?这对我来说没有多大意义,因为我不知道它如何执行这个方法。在一个门和它所连接的门之间,数据究竟是如何“传输”的?你知道吗


Tags: 对象方法fromselfnoneoutputconnectorget
1条回答
网友
1楼 · 发布于 2024-10-03 09:12:19

当gate没有收到来自用户的任何输入时,管脚实际上是连接器,如这个解释器会话所示:

>>> g1 = AndGate("g1")
>>> g2 = AndGate("g2")
>>> g3 = OrGate("g3")
>>> g4 = NotGate("g4")
>>> c1 = Connector(g1,g3)
>>> c2 = Connector(g2,g3)
>>> c3 = Connector(g3,g4)
>>> repr(g4)
'<__main__.NotGate object at 0x102958890>'
>>> g4.pin
<__main__.Connector object at 0x10297f450>
>>> g4.pin == c3
True
>>> g3.pin_a
<__main__.Connector object at 0x10297f590>
>>> g3.pin_a == c1
True
>>> g3.pin_b == c2
True
>>> g1.pin_a
>>> print(g1.pin_a)
None
>>> 

现在我明白他们是如何执行这个方法的了。你知道吗

相关问题 更多 >