用文字描述一下这段代码class SchoolMem: def __init__(self, name, sex, age): self.name = name self.sex = sex self.age = age def Alter(self): self.name = input('姓名') self.sex = input('性别') self.age = input('年龄') def PrintInfo(self): print(self.name) print(self.sex) print(self.age) class Student(SchoolMem): total = 0 def __init__(self, name, sex, age): # super()解决父类查询问题。 super().__init__(name, sex, age) Student.total += 1 def PrintInfo(self): super(Student, self).PrintInfo() class Teacher(SchoolMem): total = 0 def __init__(self, name, sex, age, sl, jno,xy): super().__init__(name, sex, age) self.cono = sl self.jno = jno self.xy=xy Teacher.total += 1 def PrintInfo(self): super(Teacher, self).PrintInfo() print(self.cono) print(self.jno) print(self.xy) a = Student('姓名:张三', '性别:男', '年龄:18') a.PrintInfo() print("\n") b = Teacher('姓名:李四', '性别:男', '年龄:30', 1,'学号:1351332133','土木学院') b.PrintInfo()
时间: 2023-12-23 22:02:24 浏览: 103
这段代码定义了三个类:SchoolMem、Student和Teacher。
SchoolMem类有三个属性:name、sex和age,以及三个方法:Alter()用于修改属性值,PrintInfo()用于打印属性值。
Student类继承自SchoolMem类,新增了一个类属性total和一个构造函数,构造函数使用super()函数调用父类的构造函数,并且在每次创建新的Student对象时total属性值加1。此外,Student类还重写了PrintInfo()方法,使用super()函数调用父类的PrintInfo()方法。
Teacher类也继承自SchoolMem类,新增了三个属性:cono、jno和xy,以及一个构造函数,构造函数同样使用super()函数调用父类的构造函数并且在每次创建新的Teacher对象时total属性值加1。Teacher类同样重写了PrintInfo()方法,先使用super()函数调用父类的PrintInfo()方法,然后打印新增的属性值。
最后,该代码创建了一个Student对象a和一个Teacher对象b,并调用它们的PrintInfo()方法,分别打印出它们的属性值。
相关问题
class Person: def __init__ (self,name,age,sex): self.name=name self.age=age self.sex=sex def personInfo(self): print("姓名:",self.name,"年龄:",self.age,"性别:",self.sex) class Student(Person): def __init__(se请帮我修改完善代码
class Person:
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def personInfo(self):
print("姓名:", self.name, "年龄:", self.age, "性别:", self.sex)
class Student(Person):
def __init__(self, name, age, sex, school):
super().__init__(name, age, sex)
self.school = school
def studentInfo(self):
print("姓名:", self.name, "年龄:", self.age, "性别:", self.sex, "学校:", self.school)
# 示例调用
p1 = Person("张三", 20, "男")
p1.personInfo()
s1 = Student("李四", 18, "女", "清华大学")
s1.personInfo()
s1.studentInfo()
class Person: def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex def getSex(self): return self.sex class Teacher(Person): def __init__(self, name, age, sex, course, salary): Person.__init__(self, name, age, sex) self.course = course self.salary = salary def getSex1(self): super().getSex() p1 = Teacher("Anna", 30, "woman", "English", 8000) print(p1.getSex1()) 为什么输出None
输出为None是因为在getSex1方法中没有返回任何值。当没有明确返回值时,默认返回None。你可以在getSex1方法中添加return语句来返回性别。例如:
```python
class Teacher(Person):
def __init__(self, name, age, sex, course, salary):
Person.__init__(self, name, age, sex)
self.course = course
self.salary = salary
def getSex1(self):
return super().getSex()
p1 = Teacher("Anna", 30, "woman", "English", 8000)
print(p1.getSex1())
```
这样就会输出"woman",表示性别为女性。
阅读全文