python類模擬電路實現


實現電路:

實現方法:

class LogicGate(object):
    def __init__(self, n):
        self.name = n
        self.output = None

    def get_label(self):
        return self.name

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


class BinaryGate(LogicGate):
    def __init__(self, n):
        super().__init__(n)
        self.pinA = None
        self.pinB = None

    def get_pinA(self):
        if self.pinA == None:
            return int(input("輸入PinA的值 " + self.get_label() + "-->"))
        else:
            return self.pinA.get_from().get_output()

    def get_pinB(self):
        if self.pinB == None:
            return int(input("輸入PinB的值 " + self.get_label() + "-->"))
        else:
            return self.pinB.get_from().get_output()

    def set_next_pin(self, source):
        if self.pinA == None:
            self.pinA = source
        else:
            if self.pinB == None:
                self.pinB = source
            else:
                print("無法連接:這個邏輯門沒有空引腳")


class AndGate(BinaryGate):
    def __init__(self, n):
        super().__init__(n)

    def perform_gate_logic(self):
        a = self.get_pinA()
        b = self.get_pinB()
        return a & b


class OrGate(BinaryGate):
    def __init__(self, n):
        super().__init__(n)

    def perform_gate_logic(self):
        a = self.get_pinA()
        b = self.get_pinB()
        return a | b


class UnaryGate(LogicGate):
    def __init__(self, n):
        super().__init__(n)
        self.pin = None

    def get_pin(self):
        if self.pin == None:
            return int(input("輸入Pin的值 " + self.get_label() + "-->"))
        else:
            return self.pin.get_from().get_output()

    def set_next_pin(self, source):
        if self.pin == None:
            self.pin = source
        else:
            print("無法連接:這個邏輯門沒有空引腳")


class NotGate(UnaryGate):
    def __init__(self, n):
        super().__init__(n)

    def perform_gate_logic(self):
        a = self.get_pin()
        return 0 if a else 1


class Connector(object):
    def __init__(self, fgate, tgate):
        self.from_gate = fgate
        self.to_gate = tgate
        tgate.set_next_pin(self)

    def get_from(self):
        return self.from_gate

    def get_to(self):
        return self.to_gate


def main():
    g1 = AndGate("U1")
    g2 = AndGate("U2")
    g3 = OrGate("U3")
    g4 = NotGate("U4")
    c1 = Connector(g1, g2)
    c2 = Connector(g2, g3)
    c3 = Connector(g3, g4)
    print(g4.get_output())

main()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM