student.md 1.8 KB
Newer Older
F
feilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
# Python 类成员

类成员变量可以直接访问,直接调用学生类的成员变量,打印学生信息

```python
# -*- coding: UTF-8 -*-
class Student:
    # TODO(You): 请在此实现含有no/name/age 三个成员属性的学生类

def test():
    students = []
    for i in range(0, 3):
        s = Student(i, f'somebody_{i}', 20+i)
        students.append(s)

    for s in students:
        print('')
        print(f"* no:{s.no}")
        print(f"* name:{s.name}")
        print(f"* age:{s.age}")

if __name__ == '__main__':
    test()
```

以下对Student的实现, **功能不正确** 的代码是?。

## template

```python
class Student:
    def __init__(self, no, name, age):
        self.no = no
        self.name = name
        self.age = age

def test():
    students = []
    for i in range(0, 3):
        s = Student(i, f'somebody_{i}', 20+i)
        students.append(s)

    for s in students:
        print('')
        print(f"* no:{s.no}")
        print(f"* name:{s.name}")
        print(f"* age:{s.age}")

if __name__ == '__main__':
    test()
```

## 答案

```python
# 普通初始化函数添加成员
class Student:
    def __init__(no, name, age):
        self.no = no
        self.name = name
        self.age = age
```

## 选项

### A

```python
# 使用 @dataclass 可以简化实现
from dataclasses import dataclass

@dataclass
class Student:
    no: int
    name: str
    age: int
```

### B

```python
# 普通初始化函数添加成员
class Student:
    def __init__(self, no, name, age):
        self.no = no
        self.name = name
        self.age = age
```

### C

```python
# 使用 @dataclass + slot 可以简化实现并且优化内存占用
from dataclasses import dataclass

@dataclass
class Student:
    __slots__ = ['no', 'name', 'age']
    no: int
    name: str
    age: int
```