python面向对象编程(很重要)

Posted masterhu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python面向对象编程(很重要)相关的知识,希望对你有一定的参考价值。


class LogicGate():
def __init__(self,n):
self.name=n
def getname(self):
return self.name
def getoutput(self):
output=self.out()
return 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.getname()+‘-->‘))
else:
return self.pinA.getfrom().out()

def getpinB(self):
if self.pinB==None:
return int(input(‘Enter pin B input for gate ‘+self.getname()+‘-->‘))
else:
return self.pinB.getfrom().out() #pinB不能去掉,如果去掉BinaryGate类没有getfrom方法,还是有点疑问

def setnextpin(self, source):
if self.pinA == None:
self.pinA = source
elif self.pinB == None:
self.pinB = source
else:
print(‘Cannot Connect: NO EMPTY PINS on this gate‘)
class Unary(LogicGate):
def __init__(self,n):
super(Unary, self).__init__(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().out()

def setnextpin(self, source):
if self.pin == None:
self.pin = source
else:
print(‘Cannot Connect: NO EMPTY PINS on this gate‘)


class andgate(BinaryGate):
def __init__(self,n):
super(andgate,self).__init__(n)
def out(self):
self.pinA=self.getpinA()
while (self.pinA != 0)and(self.pinA != 1):
self.pinA = self.getpinA()
self.pinB=self.getpinB()
while (self.pinB != 0)and(self.pinB != 1):
self.pinB = self.getpinB()
return self.pinA & self.pinB


class OrGate(BinaryGate):
def __init__(self,n):
super(OrGate, self).__init__(n)
def out(self):
self.pinA=self.getpinA()
while (self.pinA != 0)and(self.pinA != 1):
self.pinA = self.getpinA()
self.pinB=self.getpinB()
while (self.pinB != 0)and(self.pinB != 1):
self.pinB = self.getpinB()
return self.pinA | self.pinB
class NotGate(Unary):
def __init__(self,n):
super(NotGate, self).__init__(n)
self.pin=None
def out(self):
self.pin = self.getpin()
while (self.pin != 0) and (self.pin != 1):
self.pin = self.getpin()
if self.pin==1:
result=0
elif self.pin==0:
result=1
else:
print(‘input is an error!‘)
return result


class Connector():
def __init__(self,fromgate,togate):
self.fromgate=fromgate
self.togate=togate
self.togate.setnextpin(self) #连接器往下流选择pinA还是pinB
def getfrom(self):
return self.fromgate
def getto(self):
return self.togate


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.out())









































































































以上是关于python面向对象编程(很重要)的主要内容,如果未能解决你的问题,请参考以下文章

面向对象编程其实很简单——Python 面向对象(初级篇)

python面向对象编程

Python面向对象编程类

python:面向对象和类

python 面向对象

python学习笔记:面向对象编程类