接口、实现和多态
程序员文章站
2022-03-04 13:33:21
...
接口是软件资源用户可以用的一组操作,包括方法和函数以及它们的文档。
遍历集合的for循环 == “语法糖”
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
@author: liudaoqiang
@file: studycase
@time: 2018/8/30 6:51
'''
from arrayss import Array
class ArrayBag(object):
""" An array-based bag implementation"""
# Class variable
DEFAULT_CAPACITY = 10
# Constructor
def __init__(self, sourceCollection=None):
"""Sets the initial state of self, which includes the contents of sourceCollection,
if it`s present """
self._items = Array(ArrayBag.DEFAULT_CAPACITY)
self._size = 0
if sourceCollection:
for item in sourceCollection:
self.add(item)
# Accessor methods
def isEmpty(self):
"""Returns True if len(self) == 0, or False otherwise."""
return len(self) == 0
def __len__(self):
"""Returns the logical number of items in self"""
return self._size # 返回逻辑大小
# Mutator methods
def clear(self):
"""Makes self become empty"""
self._size = 0
self._items = Array(ArrayBag.DEFAULT_CAPACITY)
def add(self, item):
"""Add item to self"""
# check array memmory here and increase it if necessary
self._items[len(self)] = item
self._size += 1
def __iter__(self):
"""Supports iteration over a view of self"""
cursor = 0
while cursor < len(self):
yield self._items[cursor] # 通过yield方法,将每一项都发送给for循环调用
cursor += 1
def __str__(self):
"""returns the string representation of self"""
return "{" + ", ".join(map(str, self)) + "}"
def __add__(self, other):
"""returns a new bag containing the contents of self and other"""
result = ArrayBag(self)
for item in other:
result.add(item)
return result
def __eq__(self, other):
"""returns true if self equals other, or false otherwise"""
if self is other: return True
if type(self) != type(other) or \
len(self) != len(other):
return False
for item in self:
if item not in other:
return False
return True
def remove(self, item):
"""check precondition and raise if necessary"""
if item not in self:
raise KeyError(str(item) + " not in bag")
targetIndex = 0
for targetItem in self:
if targetItem == item:
break
targetIndex += 1
for i in range(targetIndex, len(self) - 1):
self._items[targetIndex] = self._items[targetIndex + 1]
self._size -= 1
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
@author: liudaoqiang
@file: studycase
@time: 2018/8/31 7:44
'''
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
def __iter__(self):
# 链表必须是可迭代的,才能被加入到LinkedBag实例对象中
cursor = self
while cursor != None:
yield cursor.data
cursor = cursor.next
class LinkedBag(object):
def __init__(self, sourceCollection=None):
self._items = None
self._size = 0
if sourceCollection != None:
for item in sourceCollection:
self.add(item)
def isEmpty(self):
return len(self) == 0
def __len__(self):
return self._size
def __add__(self, other):
result = LinkedBag(self)
for item in other:
result.add(item)
return result
def __eq__(self, other):
if self == other:
return True
if type(self) != type(other) or \
len(self) != len(other):
return False
for item in self:
if item not in other:
return False
return True
def __str__(self):
return "{" + ", ".join(map(str, self)) + "}"
def __iter__(self):
cursor = self._items
while cursor != None:
yield cursor.data
cursor = cursor.next
def add(self, item):
self._items = Node(item, self._items)
self._size += 1
def removeItem(self, targetItem):
"""删除元素"""
if targetItem not in self:
raise KeyError(str(targetItem) + "not in bag")
probe = self._items
trailor = None
for item in self:
if targetItem == item:
break
trailor = probe
probe = probe.next
if probe == self._items: #如果probe没有移动
self._items = self._items.next # 要删除的item就是第一个元素
else:
trailor.next = probe.next # trailor是probe的前一个节点,probe就是要删除的节点
self._size -= 1
def removeIndex(self, index):
"""删除下标对应的元素"""
if index >= self.__len__():
raise KeyError(index + "not in bag")
else:
probe = self._items
if index <= 0 or self._items.next == None:
self._items = self._items.next
else:
while index > 1 and self._items.next.next != None:
probe = probe.next
index -= 1
probe.next = probe.next.next
return self._items
if __name__ == "__main__":
lyst = list(range(6, 1, -1))
# print(lyst)
head = None
for count in range(5):
head = Node(lyst[count], head)
probe = head
linkedBag = LinkedBag(probe)
linkedBag.removeItem(4) # {6, 5, 3, 2}
linkedBag.removeIndex(1) # {6, 3, 2}
print(linkedBag)
"""
2
3
4
5
6
"""
probe = head
while probe != None:
print(probe.data)
probe = probe.next
python单元测试模块
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
@author: liudaoqiang
@file: studycase
@time: 2018/8/31 20:56
'''
from linked import LinkedBag
from arraybag import ArrayBag
def test(bagType):
""""""
lyst = [2013, 61, 1973]
print("The list of item added is", lyst)
b1 = bagType(lyst)
print("Expect 3", len(b1))
print("Expect the bag`s string", b1)
print("Expect True", 2013 in b1)
for item in b1:
print(item)
b1.clear()
print("Expect():", b1)
b1.add(25)
b1.removeItem(25)
print("Expect ():", b1)
b1 = bagType(lyst)
print("Expect string:", b1)
b2 = bagType(b1)
print("Expect True:", b1 == b2)
print("Expect False:", b1 is b2)
print("Expect two of each item", b1 + b2)
for item in lyst:
b1.removeItem(item)
print("Expect {}", b1)
print("Expect crash with KeyError:")
b2.removeItem(99)
"""
The list of item added is [2013, 61, 1973]
Traceback (most recent call last):
Expect 3 3
Expect the bag`s string {1973, 61, 2013}
Expect True True
File "F:/Github/py-evm/test.py", line 38, in <module>
1973
test(LinkedBag)
61
2013
File "F:/Github/py-evm/test.py", line 37, in test
Expect(): {}
b2.removeItem(99)
Expect (): {}
File "F:\Github\py-evm\linked.py", line 77, in removeItem
raise KeyError(str(targetItem) + "not in bag")
KeyError: '99not in bag'
Expect string: {1973, 61, 2013}
Expect True: True
Expect False: False
Expect two of each item {1973, 61, 2013, 2013, 61, 1973}
Expect {} {}
Expect crash with KeyError:
Process finished with exit code 1
"""
test(LinkedBag)
推荐阅读
-
使用Spring Boot和AspectJ实现方法跟踪基础结构
-
PHP中实现获取IP和地理位置类分享_PHP
-
Vue实现动态添加或者删除对象和对象数组的操作方法
-
PHP MYSQL实现登陆和模糊查询两大功能,mysql模糊查询
-
有道搜索和IP138的IP的API接口(PHP应用)_php实例
-
nodejs实现图片预览和上传的示例代码
-
在kettle中实现数据验证和检查
-
PHP使用反射机制实现查找类和方法的所在位置_PHP
-
透视变换原理和变换矩阵的python实现
-
python逆透视变换试验——利用cv2.getPerspectiveTransform和cv2.warpPerspective函数实现