Python学习笔记:创建分数类

Python学习笔记:创建分数类

 

Python学习笔记:创建分数类_第1张图片

1、编写创建分数类.py

# 创建分数类

from math import gcd

# 定义分数类
class Fraction:    
    def __init__(self, top, bottom):
        if type(top) == int and type(bottom) == int:
            common = gcd(top, bottom)
            self.num = top // common
            self.den = bottom // common      
        else:
            raise ValueError('错误:分子或分母不是整数!')        
    
    def getNum(self):
        return self.num
    
    def getDen(self):
        return self.den
    
    def show(self):
        print(self.num, "/", self.den)
        
    def __str__(self):
        return str(self.num) + "/" + str(self.den)

    def __add__(self, other):
        newnum = self.num * other.den + self.den * other.num
        newden = self.den * other.den       
        return Fraction(newnum, newden)
     
    def __sub__(self, other):
        newnum = self.num * other.den - self.den * other.num
        newden = self.den * other.den       
        return Fraction(newnum, newden)
    
    def __mul__(self, other):
        newnum = self.num * other.num
        newden = self.den * other.den        
        return Fraction(newnum, newden)      
    
    def __truediv__(self, other):
        newnum = self.num * other.den
        newden = self.den * other.num      
        return Fraction(newnum, newden) 

    def __eq__(self, other):
        firstnum = self.num * other.den
        secondnum = other.num * self.den
        return firstnum == secondnum
    
    def __lt__(self, other):
        firstnum = self.num * other.den
        secondnum = other.num * self.den
        return firstnum < secondnum
    
    def __le__(self, other):
        firstnum = self.num * other.den
        secondnum = other.num * self.den
        return firstnum <= secondnum
    
    def __gt__(self, other):
        firstnum = self.num * other.den
        secondnum = other.num * self.den
        return firstnum > secondnum
    
    def __ge__(self, other):
        firstnum = self.num * other.den
        secondnum = other.num * self.den
        return firstnum >= secondnum
    
    def __ne__(self, other):
        firstnum = self.num * other.den
        secondnum = other.num * self.den
        return firstnum != secondnum

x = Fraction(3, 5)
y = Fraction(2, 9)
x.show()
y.show()
print("x =", x)
print("y =", y)
print("x + y =", x + y)
print("x - y =", x - y)
print("x * y =", x * y)
print("x / y =", x / y)
print("x == y:", x == y)
print("x < y:", x < y)
print("x <= y:", x <= y)
print("x > y:", x > y)
print("x >= y:", x >= y)
print("x != y:", x != y)

2、程序运行结果

Python学习笔记:创建分数类_第2张图片

3、解释说明

(1)构造方法__init__

  • 分子和分母都除以分子分母最大公约数,化成最简分数。
  • 如果分子或分母不是整数,会抛出异常。

(2)show()方法,将分数对象按照分数格式输出

(3)__str__方法,将对象转换成字符串打印输出,类似于Java实体类的toString()方法

(4)算术运算方法

__add__、__sub__、__mul__、__truediv__分别对应+、-、*、/运算符

Python学习笔记:创建分数类_第3张图片

(5)关系运算方法

__eq__、__lt__、__le__、__gt__、__ge__、__ne__对应==、<、<=、>、>=、!=运算符

Python学习笔记:创建分数类_第4张图片

(6)获取分子与分母的方法

Python学习笔记:创建分数类_第5张图片


演示类的继承


Python学习笔记:创建分数类_第6张图片

1、创建LogicGate类

Python学习笔记:创建分数类_第7张图片

2、继承LogicGate类,创建子类BinaryGate

Python学习笔记:创建分数类_第8张图片

3、继承BinaryGate类,创建子类AndGate

Python学习笔记:创建分数类_第9张图片

4、继承BinaryGate类,创建子类OrGate

Python学习笔记:创建分数类_第10张图片

5、继承LogicGate类,创建子类UnaryGate

Python学习笔记:创建分数类_第11张图片

6、继承UnaryGate类,创建子类NotGate

Python学习笔记:创建分数类_第12张图片

7、创建Connector类

Python学习笔记:创建分数类_第13张图片

Python学习笔记:创建分数类_第14张图片

8、创建主函数main()

Python学习笔记:创建分数类_第15张图片

完整代码如下:

# 演示类的继承

class LogicGate:

    def __init__(self, name):
        self.name = name
        self.output = None

    def getLabel(self):
        return self.name

    def getOutput(self):
        self.output = self.performGateLogic()
        return self.output

# 继承LogicGate类
class BinaryGate(LogicGate):
    def __init__(self, name):
        super(BinaryGate, self).__init__(name)
        self.pinA = None
        self.pinB = None

    def getPinA(self):
        if self.pinA == None:
            return int(input("Enter Pin A input for gate " + self.getLabel() + "-->"))
        else:
            return self.pinA.getFrom().getOutput()

    def getPinB(self):
        if self.pinB == None:
            return int(input("Enter Pin B input for gate " + self.getLabel() + "-->"))
        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")

# 继承BinaryGate类
class AndGate(BinaryGate):
    def __init__(self, name):
        BinaryGate.__init__(self, name)

    def performGateLogic(self): 
        a = self.getPinA()
        b = self.getPinB()
        if a == 1 and b == 1:
            return 1
        else:
            return 0

# 继承BinaryGate类
class OrGate(BinaryGate):
    def __init__(self, name):
        BinaryGate.__init__(self, name)

    def performGateLogic(self):
        a = self.getPinA()
        b = self.getPinB()
        if a == 1 or b == 1:
            return 1
        else:
            return 0

# 继承LogicGate类
class UnaryGate(LogicGate):
    def __init__(self, name):
        LogicGate.__init__(self, name)
        self.pin = None

    def getPin(self):
        if self.pin == None:
            return int(input("Enter Pin input for gate " + self.getLabel()+"-->"))
        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")

# 继承UnaryGate类
class NotGate(UnaryGate):
    def __init__(self, name):
        UnaryGate.__init__(self, name)

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

9、运行程序,查看结果

Python学习笔记:创建分数类_第16张图片

你可能感兴趣的:(Python编程)