Python类继承/逻辑门与电路examp

2024-09-20 23:02:28 发布

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

我目前正在自学Python,正在阅读“使用算法和数据结构解决问题”(Brad Miller,David Ranum)。我偶然发现了继承的基本例子。虽然我能看到它的作用,但我需要一个解释,它实际上是如何工作的。代码如下:

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 OrGate(BinaryGate):

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

    def performGateLogic(self):

        a = self.getPinA()
        b = self.getPinB()
        if a ==1 or 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.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


def main():
   g1 = AndGate("G1")
   g2 = AndGate("G2")
   g3 = OrGate("G3")
   g4 = NotGate("G4")
   c1 = Connector(g1,g3)
   c2 = Connector(g2,g3)
   c3 = Connector(g3,g4)
   print(g4.getOutput())

main()

我最怀疑的是Connector__init__中的tgate.setNextPin(self)语句。是方法调用吗?如果是的话,为什么只有一个参数调用它,而UnaryGateBinaryGate类中的setNexPin函数实际上需要两个参数?fromgate变量如何以source数组结尾?这句话真的“初始化”了吗?在

下一个困扰我的事情是,例如,当我在声明g4.getOutput()之前print(type(g4)),我得到{},但是当{}开始时,函数开始互相调用,到了调用getPin函数的地步,如果我在return self.pinA.getFrom().getOutput()之前加上{},我得到<__main__.Connector object at 0x2b387e2f74d0>,尽管self.Pin是来自g4OrGate实例的变量。一个类实例中的一个变量如何能成为另一个没有继承它的类的对象?这和setNextPin()函数的功有关吗?在

有人能给我解释一下吗,因为我是OOP新手,被这段代码弄得很困惑。谢谢您。在


Tags: selfnonesourceinputconnectorreturnifinit
1条回答
网友
1楼 · 发布于 2024-09-20 23:02:28

关于第一个问题,tgate.setNextPin(self)是一个方法调用。tgate是一个对象,可能是其中一种门类型的实例。当您访问instance.method时,Python为您提供了一个“绑定方法”对象,它的工作原理与函数非常相似,但在实际调用实例时,它将实例作为第一个参数。所以,tgate.setNextPin(self)实际上是在调用{}

你的第二个问题似乎反映了对什么是属性的误解。不要求对象的属性具有自己的类型。在各种LogicGate子类中,pin/pinA/pinB属性要么是None(表示应该提示用户输入值),要么是Connector(或其他带有getFrom方法的东西)的实例。这两个值都不是LogicGate实例。在

至于您看到的Connector实例来自何处,它将是您创建的c1到{}值之一。Connector实例将自己安装到其tgate参数的管脚上,并使用您在第一个问题中询问的setNextPin call。我真的不能和您所看到的g4门说话,因为它似乎与示例代码的main()函数中创建的g4变量不同(它是一个不同的类型),但我怀疑它是按设计工作的,只是有点混乱。尝试通过g4.pinA来访问pinX属性,而不是在方法内部检查它们,这样可能会减少一些混乱。在

下面是一些输出代码,可以帮助您更好地理解:

# create a few gates
g1 = AndGate("G1")
g2 = OrGate("G2")

# at this point, no connectors have been hooked up, so all pinX attrs are None:
print("G1 pins:", g1.pinA, g1.pinB) # "None, None"
print("G2 pins:", g2.pinA, g2.pinB) # "None, None"

# test that the gates work independently of each other:
print("G1 output:", g1.getOutput()) # will prompt for two inputs, then print their AND
print("G2 output:", g2.getOutput()) # will prompt for two inputs, then print their OR

# create a connection between the gates
c1 = Connector(g1, g2) # connects output of g1 to first available pin (pinA) of g2

# we can see that g2.pinA has changed
print("G2 pins after connection:", g2.pinA, g2.pinB)
   # "<__main__.Connector object at SomeHexAddress>, None"

# now, if we get g2's output, it will automatically request g1's output via the Connector
print("G2 output:", g2.getOutput())
   # will prompt for 2 G1 inputs, and one G2 input and print (G1_A AND G1_B) OR G2_B

如果您想更多地使用这些类,您可能需要向部分或所有类添加__str__(和/或__repr__)方法。__str__被Python用来在必要时将类的实例转换为字符串(例如当您将其作为参数传递给printstr.format)时。下面是__str__的快速__str__实现:

^{pr2}$

相关问题 更多 >

    热门问题