定义一个类:Righttriangle,这个类下有两个方法:ob._hypotenuse,ob._area,在输入直角三角形两条直角边后分别计算直角三角形的斜边与直角三角形面积。例如:
输入:3
4
输出:5.0 6.0
class Righttriangle:
def __init__(self,a,b):
self.a = a
self.b = b
def ob_hypotenuse(self):
c = self.a.__pow__(2)+self.b.__pow__(2)
c = pow(c,0.5)
return c
def ob_area(self):
s = 0.5.__mul__(self.a.__mul__(self.b))
return s
x = float(input())
y = float(input())
triangle = Righttriangle(x,y)
print(triangle.ob_hypotenuse(),triangle.ob_area())
定义一个名称为People的人员信息类,包含姓名、性别、联系电话、籍贯几个信息。定义一个方法info,输出人员信息,信息存储到列表里。通过循环轮流输入5个人员信息,信息用空格分开,换行代表输入结束,之后再通过循环遍历通过info输出人员信息。例如:
输入:
Zhangsan male 1388888 zhejiang
Lisi male 1466666 Beijing
Wangmei female 1599999 Guangdong
Feima male 167777 Guangdong
Lingting female 179999 Jiangsu
输出
['Zhangsan','male','1388888','Zhejiang']
['Lisi','male','1466666','Beijing']
['Wangmei','female','1599999','Guangdong']
['Feima','male','167777','Guangdong']
['Lingting','female','179999','Jiangsu']
class People:
def __init__(self,name,gen,tele,area):
self.name =name
self.gender = gen
self.tele = tele
self.area = area
def info(self):
lst = [self.name,self.gender,self.tele,self.area]
print(lst)
n = 5
peolst =[]
while n>0:
information = input()
inlst = information.split(sep=" ")
people = People(inlst[0],inlst[1],inlst[2],inlst[3])
peolst.append(people)
n-=1
for item in peolst:
item.info()
定义一个类Instrment,包括几个子类Erhu、Violin、Piano等,定义一个方法makesound(),使用函数去输出乐器演奏。例如:
输入:
1
小提琴
2
钢琴
3
二胡
e
结束
class Instrument:
def make_sound(self):
pass
class Erhu(Instrument):
def make_sound(self):
super().make_sound()
print('二胡')
class Piano(Instrument):
def make_sound(self):
super().make_sound()
print('钢琴')
class Violin(Instrument):
def make_sound(self):
super().make_sound()
print('小提琴')
def play(obj):
obj.make_sound()
n = int(input())
a = Erhu()
b = Violin()
c = Piano()
lst =[a,b,c]
while n>=0 and n= len(lst):
print('输入错误')
break