写Person类的子类,Student类,类内有构造 方法,有覆盖子类的方法,有新增的方法,再写一个测试类,能正确调用 子类的方法
时间: 2024-02-26 18:58:23 浏览: 74
好的,下面是一个示例代码,其中包含了一个 Person 类和它的一个子类 Student 类,以及一个测试类 TestClass,用于测试子类的方法:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print("My name is {}, and I am {} years old.".format(self.name, self.age))
class Student(Person):
def __init__(self, name, age, id):
super().__init__(name, age)
self.id = id
def introduce(self):
print("I am a student. My name is {}, and I am {} years old. My student ID is {}.".format(self.name, self.age, self.id))
def study(self):
print("I am studying.")
class TestClass:
def test(self):
p = Person("Tom", 20)
p.introduce()
s = Student("Bob", 18, "123456")
s.introduce()
s.study()
test_obj = TestClass()
test_obj.test()
```
在上面的代码中,Person 类中定义了一个构造方法和一个 introduce 方法,Student 类继承自 Person 类,并覆盖了 introduce 方法,同时新增了一个 study 方法。TestClass 类用于测试子类的方法,创建了一个 Person 对象和一个 Student 对象,并分别调用它们的方法。您可以运行上述代码,看一下输出结果是否符合预期。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)