一、实验目的及要求
1.熟练Python类定义语法;
2.掌握类成员、实例成员和私有成员、公有成员的概念;
3. 理解继承的机制;
4. 能够定义类及成员并创建对象。
二、实验仪器设备与软件环境
1.安装有Win7/Win10微型计算机系统,每人一台;
2.每台微型计算机系统连接Internet网络;
3.安装有Python IDLE。
三、实验内容
1、定义point类,具体要求如下:
(1)类中定义构造函数,实现对实例属性x和y的初始化
(2)类中定义+运算符重载函数,实现两个点对象相加运算,返回点对象,其x和y坐标分别为参与运算的两个点对象的x坐标和,y坐标和;
(3)类中定义点对象(x1,y1)转字符串方法,返回“(x1, y1)”字符串;
(4)类中定义*运算符重载函数,实现1个点对象(x1,y1)和整数K的乘法运算,返回点对象,其x和y坐标分别为(kx1, ky1);。
(5)设计point类的测试数据,并实现对point类的测试程序。
class point:
def __init__(self,x,y):
self.x=x
self.y=y
#类中定义构造函数,实现对实例属性x和y的初始化
def __add__(self, other):
return point(self.x+other.x,self.y+other.y)
#类中定义+运算符重载函数,实现两个点对象相加运算,返回点对象,其x和y坐标分别为参与运算的两个点对象的x坐标和,y坐标和;
def __str__(self):
return '('+str(self.x)+','+str(self.y)+')'
#类中定义点对象(x1,y1)转字符串方法,返回“(x1, y1)”字符串;
def __mul__(self, other):
return point(self.x*other,self.y*other)
#类中定义*运算符重载函数,实现1个点对象(x1,y1)和整数K的乘法运算,返回点对象,其x和y坐标分别为(kx1, ky1);
a=point(1,2)
b=point(3,4)
print('a+b='+str(a+b))
print('a+b='+str(a*3))
2、建立Person类,Student类和Employee类,设计类之间的继承关系,通过实现类来验证类中私有数据成员,子类和父类的继承关系,子类构造函数中调用父类构造函数,以及多态机制等知识点。
class Person:
def __init__(self,name,height,weight,age):
self.name=name
self.height=height
self.weight=weight
self.age=age
def print(self):
print("name:{} \n height:{} \n weight:{} \n age:{}".format(self.name,self.height,self.weight,self.age))
class Student:
def __init__(self,name,height,weight,age,ID):
Person.__init__(self,name,height,weight,age)
self.ID=ID
def print2(self):
print("name:{} \n height:{} \n weight:{} \n age:{} \n ID:{}".format(self.name,self.height,self.weight,self.age,self.ID))
class Employee:
def __init__(self, name, height, weight, age, salary):
Person.__init__(self, name, height, weight, age)
self.salary = salary
def print(self):
print("name:{} \n height:{} \n weight:{} \n age:{} \n salary:{}".format(self.name, self.height, self.weight,self.age, self.salary))
P=Person('qmf',180,70,20)
P.print()
S=Student('qmf',180,70,20,20202203107)
print('继承:')
S.print2()
E = Employee('qmf',180,70,20,30000)
print('重写:')
E.print()
format()函数:一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 : 来代替以前的 % 。format 函数可以接受不限个参数,位置可以不按顺序。