实验7 面向对象编程与内置模块

task1

源代码:

 1 class Account:
 2     def __init__(self, name, account_number, initial_amount = 10):
 3         self._name=name
 4         self._card_no=account_number
 5         self._balance=initial_amount
 6  
 7     def deposit(self,amount):
 8         self._balance+=amount
 9  
10     def withdraw(self,amount):
11         if self._balance<amount:
12             print('余额不足')
13             return
14  
15         self._balance-=amount
16  
17     def info(self):
18         print('持卡人姓名:',self._name)
19         print('持卡人账号:',self._card_no)
20         print('持卡人账户余额:',self._balance)
21  
22     def get_balance(self):
23         return self._balance
24  
25 def main():
26     print('测试账户1:'.center(30,'*'))
27     a1=Account('Bob','5002311',20000)
28     a1.deposit(5000)
29     a1.withdraw(4000)
30     a1.info()
31  
32     print()
33  
34     print('测试账户2:'.center(30,'*'))
35     a2=Account('Joe','5006692',20000)
36     a2.withdraw(10000)
37     a2.withdraw(5000)
38     a2.info()
39  
40 if __name__=='__main__':
41     main()
View Code

 

  运行结果:

 

实验结论:

类:类是一群具有相同属性和方法的对象的集合,是对象的抽象

对象:是由类创建出来的一个具体的存在

属性:用来描述对象的特征

方法:用来描述对象的行为

实例化:指在面向对象的编程中,用类创建对象的过程

类的封装性:指将类的属性和方法封装起来,不允许外部直接访问对象的内部信息

 

task2

源代码:

1 from shape import Rect, Circle
2 shape_lst = [Rect(5, 5, 10, 5), Circle(), Circle(1, 1, 10)]
3 for i in shape_lst:
4     i.info()
5     print(f'面积: {i.area(): .2f}')
6     print(f'周长: {i.perimeter(): .2f}')
7     print()
View Code

 

  运行结果:

 

实验结论:

类的继承:指在一个现有类的基础上创建一个新的类,构建出来的新的类会继承原有的类的属性和方法

类的多态特性:在一个类中,可以定义多个同名的方法,只要确定他们的参数个数和类型不同,就是类的多态性

模块:一个文件就是一个模块,每一个模块在python中都被看做是一个独立的文件

 

task3

源代码:

 1 from math import *
 2 m = 0
 3 s = 2
 4 def func(x):
 5     return 1/(sqrt(2*pi)*s)*(exp((-0.5)*((x-m)/s)**2))
 6  
 7  
 8  
 9 print(f'x = 1,f = {func(1):.8f}')
10 print(f'x = 3,f = {func(3):.8f}')
11 print(f'x = 5,f = {func(5):.8f}')
12 print(f'x = 7,f = {func(7):.8f}')
13 print(f'x = 9,f = {func(9):.8f}')
View Code

 

  运行结果:

posted @ 2023-06-14 01:07  娄泽涛  阅读(18)  评论(0)    收藏  举报