1.设计一个立方体类Box,定义三个属性,分别是长,宽,高。定义二个方法,分别计算并输出立方体的体积和表面积。

代码:

class box():
    def __init__(self,length,width,high):
        self.length = length
        self.width = width
        self.high = high
    def volume(self):
        print(self.length*self.width*self.high)
    def superficial(self):
        print(2*(self.length*self.width+self.length*self.high+self.width*self.high))


b1 = box(1,1,1)
b1.volume()
b1.superficial()


2.定义一个学生类,包括学号、姓名和出生日期三个属性(数据成员) ;包括一个用于给定数据成员初始值的构造函数;包含一个可计算学生年龄的方法。编写该类并对其进行测试。

代码:

import datetime

class student:
    def __init__(self,Sno,Sname,Sbarthday,Sfaction):
        self.Sage = 0
        self.Sname = Sname
        self.Sno = Sno
        self.Sbarthday = datetime.datetime.strptime(Sbarthday,"%Y-%m-%d")
        self.Setage(Sbarthday)
    def Setage(self,Sbarthday):
        if (datetime.date.today().month - self.Sbarthday.month)>=0:
            if (datetime.date.today().day - self.Sbarthday.day)<0 and (datetime.date.today().month - self.Sbarthday.month)==0:
                self.Sage = datetime.date.today().year - self.Sbarthday.year -1
            else:
                self.Sage = datetime.date.today().year - self.Sbarthday.year
        else:
            self.Sage = datetime.date.today().year - self.Sbarthday.year -1
       

student1 = student('2018061','张三','1999-10-27',68)
print("学号:{0}   姓名:{1}  年龄:{2}".format(student1.Sno,student1.Sname,student1.Sage))

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐