请编写一个Person类,至少包含三个属性,两个方法,并创建一个Person的对象(对象名为你姓名的拼音),完成对属性赋值和方法调用。 定义一个学生类继承Person类,测试子类继承父类中哪些属性和方法,当子类重写父类中某个方法时,如何让其调用父类中的方法
时间: 2023-05-26 14:03:56 浏览: 138
Java类继承代码示例,定义Person类,Student类继承自Person类,并添加其他信息
Person类代码如下:
```python
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def introduce(self):
print(f"Hi, I'm {self.name}, {self.age} years old, {self.gender}.")
def talk(self):
print("I'm talking.")
```
创建一个对象,以我的名字为例,代码如下:
```python
class TangQuan:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def introduce(self):
print(f"Hi, I'm {self.name}, {self.age} years old, {self.gender}.")
def talk(self):
print("I'm talking.")
tangquan = TangQuan('唐权', 18, '男')
tangquan.introduce()
tangquan.talk()
```
输出结果:
```
Hi, I'm 唐权, 18 years old, 男.
I'm talking.
```
定义一个学生类继承Person类,并重写父类中的talk()方法,代码如下:
```python
class Student(Person):
def __init__(self, name, age, gender, grade):
super().__init__(name, age, gender)
self.grade = grade
def introduce(self):
print(f"Hi, I'm {self.name}, {self.age} years old, {self.gender}, and in grade {self.grade} now.")
def talk(self):
super().talk()
print("But now as a student, I'm also studying.")
```
测试子类继承父类的属性和方法,以我的名字、年龄、性别和班级为例,代码如下:
```python
class TangQuan(Student):
def __init__(self, name, age, gender, grade):
super().__init__(name, age, gender, grade)
tangquan = TangQuan('唐权', 18, '男', 3)
tangquan.introduce()
tangquan.talk()
```
输出结果:
```
Hi, I'm 唐权, 18 years old, 男, and in grade 3 now.
I'm talking.
But now as a student, I'm also studying.
```
可以看到,子类继承了父类的属性和方法,并重写了talk()方法。在重写的方法中,使用了super().talk()调用了父类中的talk()方法。
阅读全文