(1) Student 类中包含姓名、成绩两个属性。 (2)分别给这两个属性定义两个方法,个方法用于设置值,另一个方法用于 获取值。(3)Student类中定义一个无参的构造方法和一个接收两个参数的构造方法,两个参数分别为姓名和成绩属性赋值。 (4)在测试类中创建两个Student对象,一个使用无参的构造方法,然后调用方法给姓名和成绩赋值,另一个使用有参的构造方法,在构造方法中给姓名和成绩赋值。
时间: 2024-02-11 16:03:37 浏览: 22
好的,这是一个关于Python的面向对象编程问题,我来回答一下。
1. 首先定义一个Student类,包含姓名、成绩两个属性,分别定义两个方法用于设置值和获取值:
```python
class Student:
def __init__(self, name='', score=0):
self.name = name
self.score = score
def get_name(self):
return self.name
def set_name(self, name):
self.name = name
def get_score(self):
return self.score
def set_score(self, score):
self.score = score
```
2. 在Student类中定义一个无参的构造方法和一个接收两个参数的构造方法,两个参数分别为姓名和成绩属性赋值:
```python
class Student:
def __init__(self, name='', score=0):
self.name = name
self.score = score
def get_name(self):
return self.name
def set_name(self, name):
self.name = name
def get_score(self):
return self.score
def set_score(self, score):
self.score = score
def __init__(self):
self.name = ''
self.score = 0
```
3. 在测试类中创建两个Student对象,一个使用无参的构造方法,然后调用方法给姓名和成绩赋值,另一个使用有参的构造方法,在构造方法中给姓名和成绩赋值:
```python
class Test:
def test(self):
# 创建无参对象
stu1 = Student()
stu1.set_name('Tom')
stu1.set_score(90)
print('姓名:', stu1.get_name(), '成绩:', stu1.get_score())
# 创建有参对象
stu2 = Student('Jerry', 80)
print('姓名:', stu2.get_name(), '成绩:', stu2.get_score())
test = Test()
test.test()
```
输出结果:
```
姓名: Tom 成绩: 90
姓名: Jerry 成绩: 80
```
希望我的回答能够帮助到你!
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)