《Python程序设计》习题与答案

print('age must be integer.') return self.__age = age def setSex(self, sex):

if sex != 'man' and sex != 'woman': print('sex must be \ return self.__sex = sex def show(self): print(self.__name) print(self.__age) print(self.__sex) class Student(Person):

def __init__(self, name='', age = 30, sex = 'man', major = 'Computer'): #调用基类构造方法初始化基类的私有数据成员 super(Student, self).__init__(name, age, sex)

self.setMajor(major) #初始化派生类的数据成员 def setMajor(self, major): if not isinstance(major, str): print('major must be a string.') return

self.__major = major def show(self):

super(Student, self).show() print(self.__major) if __name__ =='__main__':

zhangsan = Person('Zhang San', 19, 'man') zhangsan.show()

lisi = Student('Li Si',32, 'man', 'Math') lisi.show()

6.2 设计一个三维向量类,并实现向量的加法、减法以及向量与标量的乘法和除法运算。

class Vecter3:

def __init__(self, x=0, y=0, z=0): self.X = x self.Y = y self.Z = z def __add__(self, n): r = Vecter3() r.X = self.X + n.X r.Y = self.Y + n.Y r.Z = self.Z + n.Z return r

def __sub__(self, n): r = Vecter3() r.X = self.X - n.X r.Y = self.Y - n.Y r.Z = self.Z - n.Z return r

def __mul__(self, n): r = Vecter3() r.X = self.X * n r.Y = self.Y * n r.Z = self.Z * n return r

def __truediv__(self, n): r = Vecter3() r.X = self.X / n r.Y = self.Y / n r.Z = self.Z / n return r

def __floordiv__(self, n): r = Vecter3() r.X = self.X // n r.Y = self.Y // n

联系客服:779662525#qq.com(#替换为@)