没有合适的资源?快使用搜索试试~ 我知道了~
20151910042-刘鹏-DSA实验02-高级语言面向对象编程实验1
需积分: 0 0 下载量 61 浏览量
2022-08-08
19:55:53
上传
评论
收藏 2.12MB DOCX 举报
温馨提示
试读
46页
云南大学数学与统计学院上机实践报告课程名称:数据结构与算法实验年级:2015级上机实践成绩:指导教师:陆正福姓名:刘鹏上机实践名称:高级语言面向对象编程实验学号
资源详情
资源评论
资源推荐
云南大学数学与统计学院数学系信息与计算科学专业
第 1 页 共 46 页
云南大学数学与统计学院
上机实践报告
课程名称:数据结构与算法实验
年级:2015 级
上机实践成绩:
指导教师:陆正福
姓名:刘鹏
上机实践名称:高级语言面向对象编程实验
学号:20151910042
上机实践日期:2017-05-14
上机实践编号:No.02
组号:
上机实践时间:上午 3、4 节
一、实验目的
1. 熟悉 Python 面向对象编程,为数据结构与算法的学习奠定实验基础
2. 熟悉教材第二章的代码片段
二、实验内容
1. 熟悉 Python 面向对象技术:封装、继承、多态、设计模式、程序代码的组织结构等
2. 调试主讲教材第二章的 Python 程序
三、实验平台
Windows 10 1703 Enterprise 中文版;
Python 3.6.0;
Wing IDE Professional 6.0.5-1 集成开发环境。
四、实验记录与实验结果分析
1 题
程序代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 2.3.1 Example: CreditCard Class
class CreditCard:
"""A consumer credit card."""
def __init__(self,customer,bank,acnt,limit):
"""Create a new credit card instance.
The initial balance is zero.
customer the name of the customer (e.g., 'John Bowman')
bank the name of the bank (e.g., 'California Savings')
acnt the acount identifier (e.g., '5391 0375 9387 5309')
limit credit limit (measured in dollars)
"""
self._customer = customer
self._bank = bank
self._account = acnt
self._limit = limit
self._balance = 0
def get_customer(self):
"""Return name of the customer."""
return self._customer
def get_bank(self):
"""Return the bank's name."""
云南大学数学与统计学院数学系信息与计算科学专业
第 2 页 共 46 页
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
return self._bank
def get_account(self):
"""Return the card identifying number (typically stored as a string)."""
return self._account
def get_limit(self):
"""Return current credit limit."""
return self._limit
def get_balance(self):
"""Return current balance."""
return self._balance
def charge(self,price):
"""Charge given price to the card, assuming sufficient credit limit.
Return True if charge was processed; False if charge was denied
"""
if price + self._balance > self._limit: # if charge would exceed limit
return False # cannot accept charge
else:
self._balance += price
return True
def make_payment(self,amount):
"""Process customer payment that reduces balance."""
self._balance -= amount
#------------------------------ main function ------------------------------
if __name__ == '__main__':
wallet = []
wallet.append(CreditCard('John Bowman','California Savings',\
'5391 0375 9387 5309',2500))
wallet.append(CreditCard('John Bowman','California Fedoral',\
'3485 0399 3395 1954',3500))
wallet.append(CreditCard('John Bowman','California Finance',\
'5391 0375 9387 5309',5000))
for val in range(1,17):
wallet[0].charge(val)
wallet[1].charge(2*val)
wallet[2].charge(3*val)
for c in range(3):
print('Customer =',wallet[c].get_customer())
print('Bank =',wallet[c].get_bank())
print('Account =',wallet[c].get_account())
print('Limit =',wallet[c].get_limit())
云南大学数学与统计学院数学系信息与计算科学专业
第 3 页 共 46 页
77
78
79
80
81
print('Balance =',wallet[c].get_balance())
while wallet[c].get_balance() > 100:
wallet[c].make_payment(100)
print('New balance =',wallet[c].get_balance())
print()
程序代码 1
运行结果:
运行结果 1
云南大学数学与统计学院数学系信息与计算科学专业
第 4 页 共 46 页
2 题
程序代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 2.3.3 Example: Multidimensional Vector Class
class Vector:
"""Represent a vector in a multidimensional space."""
def __init__(self,d):
"""Create d-dimensional vector of zeros."""
self._coords = [0] *d
def __len_(self):
"""Return the dimension of the ventor."""
return len(self._coords)
def __getitem__(self,j):
"""Return jth coordinate of vector."""
return self._coords[j]
def __setitem__(self,j,val):
"""Set jth coordinate of vector to given value."""
self._coords[j] = val
def __add__(self,other):
"""Return sum of two ventors."""
if len(self._coords) != len(other._coords): # relies on __len__ method
raise ValueError('dimensions must agree')
result = Vector(len(self._coords)) # start with ventor of zeros
for j in range(len(self._coords)):
result[j] = self[j] + other[j]
return result
def __eq__(self,other):
"""Return True if vector has same coordinates as other."""
return self._coords == other._coords
def __ne__(self,other):
"""Return True if vector differs from other."""
return not self == other # rely on existing __eq__ definition
def __str__(self):
"""Produce string representation of vector."""
return '<' + str(self._coords)[1:-1] + '>' # adapt list representation
#----------------------------- my main function -----------------------------
my_str = Vector(6)
other = Vector(6)
for i in range(6):
my_str[i] = i * (i + 1)
云南大学数学与统计学院数学系信息与计算科学专业
第 5 页 共 46 页
48
49
50
51
52
53
54
55
56
57
print('0: my_str = ',my_str._coords)
print('1: my_str[3] =',my_str.__getitem__(3))
k = Vector(6)
for i in range(6):
k[i] += i
print('2: k =',k._coords)
k.__add__(my_str)
print('3: add =',k.__add__(my_str)._coords)
print('4: other',other)
print('5: my_str == other?',my_str.__eq__(other))
程序代码 2
运行结果:
运行结果 2
分析:
类,与 C 语言的结构基本一致,结构中包含的元素是打点引用,而类中的元素,不仅可以打点引用 member,还可以
引用方法。如是而已。在程序代码 2 中,有一个比较明显的错误,导致了函数调用会出现问题,在__add__()方法下,它的
参数应该是 Vector 类的,但是直接调用会出错,因为 Vector 类并没有 len 方法,只有 Vector._coords 才有 len 方法。所以上
面的程序进行了修改。
3 题
程序代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 2.3.4 Iterators
class SequenceIterator:
"""An iterator for any of Python's sequence types."""
def __init__(self,sequence):
"""Create an iterator for the given sequence."""
self._seq = sequence # keep a reference to the underlying data
self._k = -1 # will increment to 0 on first call to next
def __next__(self):
"""Return the next element, or else raise StopIteration error."""
self._k += 1 # advance to next index
if self._k < len(self._seq):
return(self._seq[self._k]) # return the data element
else:
raise StopIteration('End') # there are no more elements
def __iter__(self):
"""By convention, an iterator must return itself as an iterator."""
return self
剩余45页未读,继续阅读
thebestuzi
- 粉丝: 31
- 资源: 311
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0