数据结构和算法分析程序猿阵线联盟-汇总各类技术干货python数据结构

2.python类

2019-04-11  本文已影响2人  那是个好男孩

写在前面

利用class定义(类定义)实现抽象数据类型.
本节从例子出发介绍class定义的使用、其结构和主要设施;下一节将进一步讨论python中基于class的编程技术,成为面向对象技术.

python把内置对象都看作是类.

0.有理数类
class Rationa10:
    def __init__(self, num, den=1):
        # self.fname形式的写法表示本类实例对象的属性 fname是属性名
        self.num = num #分子
        self.den = den #分母

    '''用于有理数相加'''    
    def plus(self, other):
        # other传另一个实例对象进去
        num = self.num * other.den + self.den * other.num
        den = self.den * other.den
        return Rationa10(num, den)
    
    def print(self):
        print(str(self.num) + '/' + str(self.den))

if __name__ == "__main__":
    r1 = Rationa10(3, 5)
    r2 = r1.plus(Rationa10(7, 15))
    r2.print()

#输出结果:80/75

1.类定义进阶

类定义的重要作用之一就是支持创建抽象的数据类型

我们将表示有理数类进行优化,它可以实现以下功能:

class Rationa10:
    @staticmethod
    def _gcd(m, n):
        if n == 0:
            m, n = n, m
        while m != 0:
            m, n = n % m, m
        return n

    def __init__(self, num, den=1):
        if not isinstance(num, int) or not isinstance(den, int):
            raise TypeError
        if den == 0:
            raise ZeroDivisionError
        sign = 1
        if num < 0:
            num, sign = -num, -sign
        if den < 0:
            den, sign = -den, -sign
        g = Rationa10._gcd(num, den)
        self._num = sign * (num//g) #分子
        self._den = den // g        #分母
        
    def num(self): return self._num

    def den(self): return self._den

    def __add__(self, another):       #用于有理数相加 +
        num = (self._num * another.den()
              + self._den * another.num())
        den = self._den * another.den()
        return Rationa10(num, den)
    
    def __sub__(self, another):       #用于有理数相加 -
        num = (self._num * another.den()
              + self._den * another.num())
        den = self._den * another.den
        return Rationa10(num, den)
    def __mul__(self, another):       #用于有理数相乘 *
        return Rationa10(self._num * another.num(),
                         self._den * another.den())
    
    def __floordiv__(self, another):  #用于有理数相除 //
        if another.num == 0:
            raise ZeroDivisionError
        return Rationa10(self._num * another.den(),
                         self._den * another.num())

    def __eq__(self, another):        #比较运算符 ==
        return self._num * another.den() == self._den * another.num()
        
    def __lt__(self, another):        #比较运算符 <
        return self._num * another.den() < self._den * another.num()

    def __gt__(self, another):        #比较运算符 >
        return self._num * another.den() > self._den * another.num()
        
    def __str__(self):                #把该类对象转换到字符串
        return str(self._num) + '/' + str(self._den) 

    def print(self):
        print(self._num, '/', self._den)

if __name__ == "__main__":
    #初始化方法的默认参数保证用整数直接创建有理数
    five = Rationa10(5)
    print(five)
    print(type(five))

    x = Rationa10(3, 5)
    #实例化对象x调用该类中的实例方法print()
    x.print()

    #由于有理数类定义了str转换函数,可以直接用标准函数print输出
    print("Two thirds are", Rationa10(2, 3))  
    #使用类中定义的算术运算符和条件运算符
    y = five + x * Rationa10(5, 17)
    print(y)
    if y < Rationa10(123, 11):
        print("small")

结果输出如下:

5/1
<class '__main__.Rationa10'>
3 / 5
Two thirds are 2/3
88/17
small

代码解析:


2.python采用的ADT描述形式

为了更好的用python面向对象的技术和类结构定义各种数据类型,使用的ADT描述将模仿python类定义的形式,也认为ADT描述的是一个类型

ADT描述形式python
上一篇 下一篇

猜你喜欢

热点阅读