对象的信息我想要手动输入,请给我完整代码
时间: 2024-10-24 07:09:54 浏览: 35
当然,如果你想手动输入创建对象所需的信息,可以像下面这样编写代码。这里是一个示例,首先定义`Person`类和`Student`类,然后通过`input()`函数获取用户输入的数据:
```python
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = int(age) # 将字符串年龄转换为整数
self.gender = gender
def personInfo(self):
print(f"姓名:{self.name}, 年龄:{self.age}, 性别:{self.gender}")
def __str__(self):
return f"{self.name} ({self.age}) - {self.gender}"
class Student(Person):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) # 继承父类的初始化方法
def personInfo(self):
super().personInfo()
print(f"学院:{self.college}, 班级:{self.class_}")
def study(self, teacher):
print(f"正在向{teacher.name}学习...") # 这里假设已经有了teacher对象,实际应用中需要提供更完整的代码
def __str__(self):
return super().__str__() + "\n学院:" + self.college + ", 班级:" + self.class_
# 获取用户输入并创建对象
name = input("请输入学生姓名:")
age = input("请输入年龄:")
gender = input("请输入性别:")
college = input("请输入学院:")
class_ = input("请输入班级:")
# 定义一个简单的teacher对象(仅用于演示)
teacher_name = "张老师"
student = Student(name, age, gender, college, class_, teacher_name)
# 执行对象的相关操作
student.personInfo()
student.study(teacher_name)
# 打印学生信息
print(student)
```
运行此代码后,你会看到提示,让用户逐项输入学生和教师的信息。请注意,这只是一个基本示例,实际应用中你需要处理数据验证和错误检查。
阅读全文
相关推荐

















