- 定义一个Person类拥有设置姓名、年龄、性别的成员方法;
- 定义派生类Teacher继承Person类,并拥有自己的show()方法;
- 定义派生类Student继承Person类,并拥有自己的show()方法;
class Person(object):
def __init__(self, name = '', age = 20, sex = 'man'):
self.setName(name)
self.setAge(age)
self.setSex(sex)
def setName(self, name):
if not isinstance(name, str):
print('name must be string')
return
self.__name = name
def setAge(self, age):
if not isinstance(age, int):
print('age must be integer')
return
self.__age = age
def setSex(self, sex):
if sex not in ('man', 'woman'):
print('sex must be "man" or "woman"')
self.__sex = sex
def show(self):
print('Name:', self.__name)
print('Age:', self.__age)
print('Sex:', self.__sex)
class Teacher(Person):
def __init__(self, name='', age = 30, sex = 'man', department = 'Computer'):
super(Teacher, self).__init__(name, age, sex)
self.setDepartment(department)
def setDepartment(self, department):
if not isinstance(department, str):
print('department must be a string.')
return
self.__department = department
def show(self):
super(Teacher, self).show()
print('Department:', self.__department)
class Student(Person):
def __init__(self, name='', age = 20, sex = 'man', department = 'Computer'):
Person.__init__(self, name, age, sex)
self.setDepartment(department)
def setDepartment(self, department):
if not isinstance(department, str):
print('department must be a string.')
return
self.__department = department
def show(self):
Person.show(self)
print('Department:', self.__department)
if __name__ =='__main__':
print('='*30)
zhangsan = Person('Zhang San', 19, 'man')
zhangsan.show()
print('='*30)
lisi = Teacher('Li Si',32, 'man', 'Math')
lisi.show()
print('='*30)
lisi.setAge(40)
lisi.show()
print('='*30)
wangwu = Student('Wang Wu',21, 'man', 'Math')
wangwu.show()