es定义一个Person类,属性有姓名和年龄,方法有显示自身信息show,继承类为Stu类,添加属性学号,方法添加一个学习study,实例化对象调用相应的方法。
时间: 2024-03-11 16:49:42 浏览: 59
好的,以下是代码实现:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def show(self):
print("姓名:{},年龄:{}".format(self.name, self.age))
class Stu(Person):
def __init__(self, name, age, stu_id):
super().__init__(name, age)
self.stu_id = stu_id
def study(self):
print("{}正在学习".format(self.name))
# 实例化对象
person1 = Person("张三", 20)
person1.show()
stu1 = Stu("李四", 18, "20210001")
stu1.show()
stu1.study()
```
输出结果:
```
姓名:张三,年龄:20
姓名:李四,年龄:18
李四正在学习
```
相关问题
设计一个人类Person,其内部有一个name属性,一个call()方法,输出姓名。 再设计一个学生类Student,继承自Person类,学生类有一个自己的属性stu_number学号。重写__init__方法和call方法,输出学号和姓名。
好的,我可以为您编写这两个类的代码。Python代码如下:
```python
class Person:
def __init__(self, name):
self.name = name
def call(self):
print("My name is", self.name)
class Student(Person):
def __init__(self, name, stu_number):
super().__init__(name)
self.stu_number = stu_number
def call(self):
print("My name is", self.name, "and my student number is", self.stu_number)
```
使用方法如下:
```python
person = Person("Tom")
person.call()
student = Student("Jerry", "20210001")
student.call()
```
输出:
```
My name is Tom
My name is Jerry and my student number is 20210001
```
希望这个代码能够帮到您!
(创建父类Person属性有姓名年龄方法有两个构造方法,1个普通方法用于显示姓名和年龄,还有针对属性的输入输出方法创建子类Student属性有学号方法有两个构造方法;1个普通方法用于显示学号,姓名,年龄;创建测试类StudentTest进行测试。)的代码是什么
以下是代码示例:
//父类Person
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
this.name = "";
this.age = 0;
}
public void showNameAndAge() {
System.out.println("姓名:" + name + ",年龄:" + age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//子类Student
public class Student extends Person {
private String stuNo;
public Student(String name, int age, String stuNo) {
super(name, age);
this.stuNo = stuNo;
}
public Student() {
super();
this.stuNo = "";
}
public void showStuInfo() {
System.out.println("学号:" + stuNo + ",姓名:" + getName() + ",年龄:" + getAge());
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
}
//测试类StudentTest
public class StudentTest {
public static void main(String[] args) {
Student stu = new Student("小明", 18, "20210001");
stu.showStuInfo();
}
}
阅读全文