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类的测试程序。
Code:
class point:
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self, other):
t1 = self.x + other.x
t2 = self.y + other.y
return point(t1,t2)
def __mul__(self, other):
return point(self.x*other,self.y*other)
def work(self):
return str((self.x,self.y))
p1 = point(2,3)
p2 = point(4,4)
p3 = p1+p2
print(p3.x,p3.y)
print(point.work(p3))
print(type(point.work(p3)))
p4 = p1*3
print(p4.x,p4.y)
2、建立Person类,Student类和Employee类,设计类之间的继承关系,通过实现类来验证类中私有数据成员,子类和父类的继承关系,子类构造函数中调用父类构造函数,以及多态机制等知识点。
Code:
class Person:
__vis = 20
kk = "python"
def __init__(self,name,age):
self.name = name
self.age = age
def info(self):
print("name:{0},age:{1}".format(self.name,self.age))
class Student(Person):
def __init__(self,name,age,score):
super().__init__(name,age)
self.score = score
def info(self):
super().info()
print("score:",self.score)
class Employee(Person):
def __init__(self,name,age,slary):
super().__init__(name,age)
self.slary = slary
def info(self):
super().info()
print("slary",self.slary)
class test:
def info(self):
print("我是测试类")
p1 = Person("张三",20)
stu1 = Student("李四",18,88)
e1 = Employee("Jack",25,18888)
print("----------封装-------------")
print(Person.kk)
p2 = Person("abc",19)
p2.gender = "male"
def show_gender():
print(p2.gender)
p2.show_gender = show_gender
print(p2.name,p2.age,p2.gender)
p2.show_gender()
print("----------继承-------------")
p1.info()
stu1.info()
e1.info()
print("----------多态-------------")
def work(tep):
tep.info()
work(p1)
work(stu1)
work(e1)
work(test())
|