Python学习笔记-初级(五):面向对象

来源:互联网 发布:matlab如何数据预测 编辑:程序博客网 时间:2024/04/28 14:28

一、问题背景

“Python语言导论“课程作业:

1、  编写平面坐标处理的类,其中,需满足如下要求:

(1)   有“__eq__”方法(def __eq__(self, other):),若坐标被认为是平面上的同一个点则返回真(即有同样的x,y坐标)。
(2) 定义一个特殊方法__repr__(def __repr__(self):),能够输出形式如“Coordinate(1, 8)”的坐标。
(3) 完成如下操作:
* 创建一个坐标为(1,8)的对象
* 分别用str方法和repr方法显示该对象
* 再创建一个坐标为(1,8)的对象
* 判断这两个对象是否相等?


2、  创建一个新类表示整数集合
(1)   初始时集合为空
(2)   每个特定的整数只能在集合中出现一次(注:必须在方法中强制实现)
(3)   内部数据表示:用一个列表存储集合中的元素 
(4)   接口
* insert(e):若整数e不存在,则插入e到集合中
* member(e):若整数e在集合中返回True,否则返回False
* remove(e):从集合中删除整数e,若不存在则出错

(5)   定义一个方法intersect(self, other),返回一个新的intSet,包含同时出现在两个集合中的元素。换句话说,
s1.intersect(s2),将返回同时包含在s1和s2中元素的新intSet。若s1和s2没有共同的元素该如何处理?

(6)   增加一个特殊方法__len__(self),若调用len(s),将返回s中元素的个数。


二、代码

1、  coordinate.py: 

<span style="font-size:14px;">'''Author: WJTDate: 11/4/2016Function: deal with the coordinate of the points in a plane'''# class Coordinate to deal with the coordinate of the point in a planeclass Coordinate(object):    # construction function    def __init__(self, x, y):        self.x = x        self.y = y        # public function for getting the coordinate x    def getX(self):        return self.x        # public function for getting the coordinate y    def getY(self):        return self.y    # private function for specific format print    # overload of inner function "str"     def __str__(self):        return '<' + str(self.getX()) + ',' + str(self.getY()) + '>'    # private function for comparing two Coordinate objects    # called implicitly when comparing    def __eq__(self, other):        if ((self.x == other.x) and (self.y == other.y)):            return True        else:            return False                # private function for specific format print    # overload of inner function "repr"     def __repr__(self):        return 'Coordinate<' + str(self.x) + ', ' +  str(self.y) + '>'# test bench if __name__ == '__main__':    obj1 = Coordinate(1, 8)    print(str(obj1))    print(repr(obj1))    obj2 = Coordinate(1, 8)    print(obj1 == obj2)</span>


2、  intSet.py:

'''Author: WJTDate: 11/4/2016Function: class for integer set'''class intSet(object):    """    An intSet is a set of integers    The value is represented by a lis of ints, self.vals.    Each int in the set occurs in self.vals exactly once.    """    def __init__(self):        """Create an empty set of integers"""        self.vals = []    def insert(self, e):        """Assumes e is an integer and insert e into self.vals"""        if not e in self.vals:  # e not in self.vals            self.vals.append(e)    def member(self, e):        """Assumes e is an integer        return True if e is in self and False otherwise"""                return e in self.vals    def remove(self, e):        """Assumes e is an integer and remove e from self        Raise ValueError if e is not in self"""        # try-except statements to deal with error        try:            self.vals.remove(e)        except:            raise ValueError(str(e) + 'not found')    def __str__(self):        "return a string representation of self"        self.vals.sort()        return '{' + ','.join([str(e) for e in self.vals]) + '}'    def intersect(self, other):        newSet = intSet()        for i in self.vals:            if other.member(i):                newSet.insert(i)        return newSet    # private function for getting length    # overload of inner funtion "len"    def __len__(self):        return len(self.vals)# test benchif __name__ == '__main__':    obj_1 = intSet()    for i in range(0, 10):        obj_1.insert(i)      obj_2 = intSet()    for i in range(0, 6):        obj_2.insert(i)    # display length     print("length of obj_1: " + str(len(obj_1)))    print("length of obj_2: " + str(len(obj_2)))    # display intersection of two sets    print(obj_1.intersect(obj_2))    


三、运行结果

1、  coordinate.py:



2、  intSet.py:




0 0