Python初学,类与对象学习过程中的代码修正
父类中不存在的参数,需要在子类中重新定义和修正,采用raise Exception 函数可以简单快捷地将输入过程中的错误找出;
在重定义参数的过程中,尤其注意定义过程中代码定义格式的编写正确
如,self.setGrade(grade),缺少 set时,即写成self.Grade(grade)的格式时会产生如下报错:
'Student' object has no attribute 'Grade'
代码展示:
# father 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): raise Exception('name must be string') self.__name = name def setAge(self, age): if type(age) != int: raise Exception('age must be int') self.__age = age def setSex(self, sex): if sex not in ('man', 'woman'): raise Exception('sex must be "man" or "woman"') self.__sex = sex def show(self): print(self.__name, self.__age, self.__sex) # 派生类/son class Teacher(Person): def __init__(self, name='', age=30, sex='man', department='Computer'): super(Teacher, self).__init__(name, age, sex) self.setDepartment(department) # Person.__init__(self, name, age, sex) def setDepartment(self, department): if type(department) != str: raise Exception('department must be str') self.__department = department def show(self): super(Teacher, self).show() print(self.__department) class Student(Person): def __init__(self, name='', age='', sex='man', grade='', major=''): super(Student, self).__init__(name, age, sex) self.setGrade(grade) self.setMajor(major) def setGrade(self, grade): if type(grade) != int: raise Exception('grade must be int') self.__grade = grade def setMajor(self, major): if type(major) != str: raise Exception('major must be str') self.__major = major def show(self): super(Student, self).show() print(self.__grade) print(self.__major) if __name__ == '__main__': zhangsan = Person('Zhang San', 19, 'man') zhangsan.show() print('='*30) lisi = Teacher('L1 si', 32, 'man', 'Math') lisi.show() print('='*30) lisi.setAge(40) lisi.setDepartment('Computer') lisi.show() print('='*30) Elvin = Student('Elvin', 20, 'man', 2, 'software') Elvin.show()