class Person(): def __init__(self): super(Person, self).__init__() print("Person is here") class Teacher(Person): def __init__(self): super(Teacher, self).__init__() print("Teacher is here") t = Teacher() 执行是否可以正常执行?
时间: 2023-08-03 15:06:52 浏览: 68
可以正常执行,输出结果为:
```
Person is here
Teacher is here
```
这是因为 `Teacher` 继承自 `Person`,所以在创建 `Teacher` 对象时,会先调用 `Person` 的构造函数,再调用 `Teacher` 的构造函数。 `super()` 函数用于调用父类的方法。在这个例子中,`super(Teacher, self).__init__()` 表示调用 `Teacher` 的父类 `Person` 的构造函数。
相关问题
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方法中,没有返回super().getSex()的返回值。在Python中,如果函数没有明确的返回语句,则默认返回None。所以,当调用p1.getSex1()时,返回的就是None。要修正这个问题,可以在getSex1方法中添加return语句,将super().getSex()的返回值返回出来。例如:
```python
def getSex1(self):
return super().getSex()
```
这样,调用p1.getSex1()就会返回"woman",而不是None。
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()
阅读全文