提交 3c3d1a2e 编写于 作者: F feilong

更新第四章

上级 fff4b711
{
"multiline": [
{
"__init__": "init"
},
{
"dump(self)": "dump()"
},
{
"s = Student": "s = new Student"
}
],
"source": "student.py",
"source": "student.md",
"depends": [],
"exercise_id": 56,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 类和对象
创建学生类, 创建一个学生列表,加入3个学生,循环打印学生信息
```python
# -*- coding: UTF-8 -*-
class Student:
def __init__(self, no, name, age):
# TODO(You): 请在此初始化成员
def dump(self):
# TODO(You): 请在此打印学生信息
if __name__ == '__main__':
students = []
for i in range(0, 3):
s = Student(i, f'somebody_{i}', 20+i)
students.append(s)
for s in students:
print('')
s.dump()
```
请选出下列对Student**实现不正确**的代码。
## template
```python
class Student:
def __init__(self, no, name, age):
self.no = no
self.name = name
self.age = age
def dump(self):
print(f"* no:{self.no}")
print(f"* name:{self.name}")
print(f"* age:{self.age}")
if __name__ == '__main__':
students = []
for i in range(0, 3):
s = Student(i, f'somebody_{i}', 20+i)
students.append(s)
for s in students:
s.dump()
```
## 答案
```python
class Student:
def __init__(self, no, name, age):
self.no = no
self.name = name
self.age = age
def dump():
print(f"* no:{self.no}")
print(f"* name:{self.name}")
print(f"* age:{self.age}")
```
## 选项
### A
```python
class Student:
def __init__(self, no, name, age):
self.no = no
self.name = name
self.age = age
def dump(self):
print(f"* no:{self.no}")
print(f"* name:{self.name}")
print(f"* age:{self.age}")
```
### B
```python
class Student:
def __init__(self, no, name, age):
self.no = no
self.name = name
self.age = age
def dump(self):
infos = [
f"* no:{self.no}",
f"* name:{self.name}",
f"* age:{self.age}"
]
for info in infos:
print(info)
```
### C
```python
class Student:
def __init__(self, no, name, age):
self.fields = {
'no': no,
'name': name,
'age': age
}
def dump(self):
for field_name in self.fields:
field_value = self.fields[field_name]
print(f'* {field_name}:{field_value}')
```
{
"multiline": [
{
"no,": "_no"
},
{
"self.name = name": "self.name = _name"
},
{
"s.age": "s.age()"
}
],
"source": "student.py",
"source": "student.md",
"depends": [],
"exercise_id": 54,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# 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
```
{
"multiline": [
{
"get_no(self)": "get_no()",
"get_name(self)": "get_name()",
"get_age(self)": "get_age()",
"inc_age(self)": "inc_age()"
},
{
"self.age += 1": "self.age -= 1"
},
{
"print(s.log)": "print(s.log())"
}
],
"source": "evolope.py",
"source": "evolope.md",
"depends": [],
"exercise_id": 209,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 封装
使用类的方法获取相关信息,可以将内部的实现细节封装起来
```python
# -*- coding: UTF-8 -*-
class Student:
def __init__(self, no, name, age):
# TODO(初始化)
def no(self):
# TODO(返回编号)
def name(self):
# TODO(返回名字)
def age(self):
# TODO(返回年龄)
if __name__ == '__main__':
s = Student(0, f'somebody', 20)
print(f'* {s.no()}')
print(f'* {s.name()}')
print(f'* {s.age()}')
```
以下对Student的实现,**不正确**的代码是?
## template
```python
class Student:
def __init__(self, no, name, age):
self._no = no
self._name = name
self._age = age
def no(self):
return self._no
def name(self):
return self._name
def age(self):
return self._age
if __name__ == '__main__':
s = Student(0, f'somebody', 20)
print(f'* {s.no()}')
print(f'* {s.name()}')
print(f'* {s.age()}')
```
## 答案
```python
class Student:
def __init__(self, no, name, age):
self.no = no
self.name = name
self.age = age
def no(self):
return self.no
def name(self):
return self.name
def age(self):
return self.age
```
## 选项
### A
```python
class Student:
def __init__(self, no, name, age):
self._no = no
self._name = name
self._age = age
def no(self):
return self._no
def name(self):
return self._name
def age(self):
return self._age
```
### B
```python
class Student:
def __init__(self, no, name, age):
self.info = {
'no': no,
'name': name,
'age': age
}
def no(self):
return self.info['no']
def name(self):
return self.info['name']
def age(self):
return self.info['age']
```
### C
```python
class Student:
def __init__(self, no, name, age):
self.info =[no, name, age]
def no(self):
return self.info[0]
def name(self):
return self.info[1]
def age(self):
return self.info[2]
```
{
"multiline": [
{
"People(object)": "People : object",
"Student(People)": "Student : People",
"Teacher(People)": "Teacher : People"
},
{
"People(object)": "People implement object",
"Student(People)": "Student implement People",
"Teacher(People)": "Teacher implement People"
},
{
"super().__init__(name, age)": ""
}
],
"source": "inherent.py",
"source": "inherent.md",
"depends": [],
"exercise_id": 235,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 继承
下面是People、Student和Teacher三个类
```python
# -*- coding: UTF-8 -*-
class People(object):
def __init__(self, name, age):
self.name = name
self.age = age
class Student:
def __init__(self, no, name, age):
self.name = name
self.age = age
self.no = no
class Teacher:
def __init__(self, access_key, name, age):
self.name = name
self.age = age
self.access_key = access_key
if __name__ == '__main__':
s = Student(0, f'somebody', 20)
t = Teacher('jladfja', 'linus', 0)
print('# 教师')
print(f"* name:{t.name}")
print(f"* age:{t.age}")
print('')
print('# 学生')
print(f"* no:{s.no}")
print(f"* name:{s.name}")
print(f"* age:{s.age}")
```
实际上Student 和 Teacher 可以从 People 类继承,复用实现
请选出下列对继承对使用,**正确**的选项。
## template
```python
class People(object):
def __init__(self, name, age):
self.name = name
self.age = age
class Student(People):
def __init__(self, no, name, age):
super().__init__(name, age)
self.no = no
class Teacher(People):
def __init__(self, access_key, name, age):
super().__init__(name, age)
self.access_key = access_key
if __name__ == '__main__':
s = Student(0, f'somebody', 20)
t = Teacher('jladfja', 'linus', 0)
print('# 教师')
print(f"* name:{t.name}")
print(f"* age:{t.age}")
print('')
print('# 学生')
print(f"* no:{s.no}")
print(f"* name:{s.name}")
print(f"* age:{s.age}")
```
## 答案
```python
class Student(People):
def __init__(self, no, name, age):
super().__init__(name, age)
self.no = no
class Teacher(People):
def __init__(self, access_key, name, age):
super().__init__(name, age)
self.access_key = access_key
```
## 选项
### A
```python
class Student(People):
def __init__(self, no, name, age):
self.no = no
class Teacher(People):
def __init__(self, access_key, name, age):
self.access_key = access_key
```
### B
```python
class Student(People):
def __init__(self, no, name, age):
super.__init__(name, age)
self.no = no
class Teacher(People):
def __init__(self, access_key, name, age):
super.__init__(name, age)
self.access_key = access_key
```
### C
```python
class Student(People):
def __init__(self, no, name, age):
super(name, age)
self.no = no
class Teacher(People):
def __init__(self, access_key, name, age):
super(name, age)
self.access_key = access_key
```
{
"multiline": [
{
"super().__init__(\"student\", name, age)": ""
},
{
"super().__init__(\"teacher\", name, age)": ""
},
{
"super().infos()": "self.infos()"
},
{
"super().infos()": "super.infos()"
}
],
"source": "poly.py",
"source": "poly.md",
"depends": [],
"exercise_id": 238,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 类多态
Student 和 Teacher 类都继承 People 类。Student 和 Teacher 类可以动态改变 People 类的 infos 方法,添加子类新增信息。程序入口可以对它们统一处理,打印他们的基本信息
```python
# -*- coding: UTF-8 -*-
class People:
def __init__(self, role, name, age):
self.name = name
self.age = age
self.role = role
def infos(self):
return [
f"name:{self.name}",
f"age:{self.age}",
f"role:{self.role}"
]
class Student(People):
def __init__(self, no, name, age):
super().__init__("student", name, age)
self.no = no
def infos(self):
# TODO(You): 请在此实现学生类 infos 方法
class Teacher(People):
def __init__(self, access_key, name, age):
super().__init__("teacher", name, age)
self.access_key = access_key
def infos(self):
# TODO(You): 请在此实现教师类 infos 方法
if __name__ == '__main__':
peoples = [
Teacher("ajladfjkadf", "Linus", 0)
]
for i in range(0, 3):
s = Student(i, f'somebody_{i}', 20+i)
peoples.append(s)
for p in peoples:
print()
for info in p.infos():
print(info)
```
以下对 Student 和 Teacher 的 `infos` 方法实现正确的是?
## template
```python
class People:
def __init__(self, role, name, age):
self.name = name
self.age = age
self.role = role
def infos(self):
return [
f"name:{self.name}",
f"age:{self.age}",
f"role:{self.role}"
]
class Student(People):
def __init__(self, no, name, age):
super().__init__("student", name, age)
self.no = no
def infos(self):
info_list = super().infos()
info_list.append(f'no:{self.no}')
return info_list
class Teacher(People):
def __init__(self, access_key, name, age):
super().__init__("teacher", name, age)
self.access_key = access_key
def infos(self):
info_list = super().infos()
info_list.append(f'access_key:{self.access_key}')
return info_list
if __name__ == '__main__':
peoples = [
Teacher("ajladfjkadf", "Linus", 0)
]
for i in range(0, 3):
s = Student(i, f'somebody_{i}', 20+i)
peoples.append(s)
for p in peoples:
print()
for info in p.infos():
print(info)
```
## 答案
```python
class Student(People):
...
def infos(self):
info_list = super().infos()
info_list.append(f'no:{self.no}')
return info_list
class Teacher(People):
...
def infos(self):
info_list = super().infos()
info_list.append(f'access_key:{self.access_key}')
return info_list
```
## 选项
### A
```python
class Student(People):
...
def infos(self):
info_list = super.infos()
info_list.append(f'no:{self.no}')
return info_list
class Teacher(People):
...
def infos(self):
info_list = super.infos()
info_list.append(f'access_key:{self.access_key}')
return info_list
```
### B
```python
class Student(People):
...
def infos(self):
info_list = self.infos()
info_list.append(f'no:{self.no}')
return info_list
class Teacher(People):
...
def infos(self):
info_list = self.infos()
info_list.append(f'access_key:{self.access_key}')
return info_list
```
### C
```python
class Student(People):
...
def infos(self):
return [f'no:{self.no}']
class Teacher(People):
...
def infos(self):
return [f'access_key:{self.access_key}']
```
{
"one_line": {
"class Point": [
"def class Point"
],
"dot(self, right)": [
"dot(right)"
],
"self.x*right.x+self.y*right.y+self.z*right.z": [
"x*right.x+y*right.y+z*right.z"
],
"__init__": [
"init"
],
"= Point": [
"new = Point"
]
},
"source": "point.py",
"source": "point.md",
"depends": [],
"exercise_id": 52,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 类创建
创建点对象,有多种方式创建一个类的实例,我们称一个点的x、y、z都一样的点为对角点。
```python
# -*- coding: UTF-8 -*-
class Point:
# TODO(You): 添加代码支持类的创建
if __name__ == '__main__':
points = []
# TODO(You): 批量创建1000个对角点,第i个点的坐标是 (i,i,i)
for point in points:
print(point)
```
以下对上述代码补全,不正确的是?
## template
```python
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
if __name__ == '__main__':
points = []
for i in range(1000):
points.append(Point(i,i,i))
for point in points:
print(point)
```
## 答案
```python
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
if __name__ == '__main__':
points = []
for i in range(1000):
points.append(new Point(i,i,i))
```
## 选项
### A
```python
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
if __name__ == '__main__':
points = []
for i in range(1000):
points.append(Point(i,i,i))
```
### B
```python
# 通过 @classmethod 装饰器,增加一个类级别的创建方法,批量创建
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
@classmethod
def create_diag_points(cls, count):
# 在@classmethod修饰的方法中,其中 cls 表示 Point
points = []
for i in range(count):
points.append(cls(i,i,i))
return points
if __name__ == '__main__':
points = Point.create_diag_points(1000)
```
### C
```python
# 添加类静态方法,批量创建对角点
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
@staticmethod
def create_diag_points(count):
points = []
for i in range(count):
points.append(Point(i,i,i))
return points
if __name__ == '__main__':
points = Point.create_diag_points(1000)
```
{
"one_line": {
"@abc.abstractmethod": [
"@abstractmethod"
],
"pass": [
""
],
"import abc": [
""
]
},
"source": "abstract.py",
"source": "abstract.md",
"depends": [],
"exercise_id": 51,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 抽象类创建
使用 abc 库,创建抽象 BasePoint 类,创建 Point 子类,实现 dot 抽象方法,计算内积
```python
# -*- coding: UTF-8 -*-
import abc
# TODO(You): 请实现抽象类 BasePoint
class Point(BasePoint):
def __init__(self, x, y, z) -> None:
super().__init__(x, y, z)
def dot(self, right):
return self.x*right.x+self.y*right.y+self.z*right.z
if __name__ == '__main__':
p1 = Point(0, 1, 2)
p2 = Point(2, 4, 6)
assert p1.dot(p2) == 16
p1 = BasePoint(0, 1, 2)
p2 = BasePoint(2, 4, 6)
assert p1.dot(p2) is None
```
以下对 BasePoint 抽象类实现 **正确** 的代码是?
## template
```python
import abc
class BasePoint:
def __init__(self, x, y, z) -> None:
self.x = x
self.y = y
self.z = z
@abc.abstractmethod
def dot(self, right):
pass
class Point(BasePoint):
def __init__(self, x, y, z) -> None:
super().__init__(x, y, z)
def dot(self, right):
return self.x*right.x+self.y*right.y+self.z*right.z
if __name__ == '__main__':
p1 = Point(0, 1, 2)
p2 = Point(2, 4, 6)
assert p1.dot(p2) == 16
p1 = BasePoint(0, 1, 2)
p2 = BasePoint(2, 4, 6)
assert p1.dot(p2) is None
```
## 答案
```python
class BasePoint:
def __init__(self, x, y, z) -> None:
self.x = x
self.y = y
self.z = z
@abc.abstractmethod
def dot(self, right):
pass
```
## 选项
### A
```python
class BasePoint:
def __init__(self, x, y, z) -> None:
self.x = x
self.y = y
self.z = z
@abstractmethod
def dot(self, right):
pass
```
### B
```python
class BasePoint:
def __init__(self, x, y, z) -> None:
self.x = x
self.y = y
self.z = z
def dot(self, right):
pass
```
### C
```python
class BasePoint:
def __init__(self, x, y, z) -> None:
self.x = x
self.y = y
self.z = z
@abc.abstractmethod
def dot(self, right):
```
{
"one_line": {
"_func": [
"func"
],
"__test": [
"test",
"_test",
"__test__"
]
},
"source": "access.py",
"source": "access.md",
"depends": [],
"exercise_id": 55,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 访问控制
分别编写类内部的私有方法,模块级别的私有方法
请选出下列能**代码和注释一致**的代码。
## template
```python
class Test:
def __init__(self) -> None:
pass
def test(self):
self.__test()
def __test(self):
'''类内部的私有方法'''
print("test")
def _func():
'''模块级别的私有方法'''
print("file private")
if __name__ == '__main__':
t = Test()
t.test()
```
## 答案
```python
class Test:
def test(self):
self.__test()
def __test(self):
'''类内部的私有方法'''
print("test")
def _func():
'''模块级别的私有方法'''
print("file private")
if __name__ == '__main__':
t = Test()
t.test()
```
## 选项
### A
```python
class Test:
def test(self):
self._test()
def _test(self):
'''类内部的私有方法'''
print("test")
def _func():
'''模块级别的私有方法'''
print("file private")
if __name__ == '__main__':
t = Test()
t.test()
```
### B
```python
class Test:
def test(self):
self.__test__()
def __test__(self):
'''类内部的私有方法'''
print("test")
def _func():
'''模块级别的私有方法'''
print("file private")
if __name__ == '__main__':
t = Test()
t.test()
```
### C
```python
class Test:
def test(self):
self.__test()
def __test(self):
'''类内部的私有方法'''
print("test")
def func():
'''模块级别的私有方法'''
print("file private")
if __name__ == '__main__':
t = Test()
t.test()
```
{
"one_line": {
"hasattr": [
"has",
"attr",
"contains"
],
"getattr": [
"get",
"attr"
]
},
"source": "object_meta.py",
"source": "object_meta.md",
"depends": [],
"exercise_id": 53,
"type": "code_options"
"type": "code_options",
"author": "huanhuilong",
"notebook_enable": true
}
\ No newline at end of file
# Python 获取对象信息
过滤列表里所有含有 'z' 属性的对象,打印他们的 'x'+'y'+'z' 的值
```python
# -*- coding: UTF-8 -*-
class Point2D:
def __init__(self, x, y) -> None:
self.x = x
self.y = y
class Point3D:
def __init__(self, x, y, z) -> None:
self.x = x
self.y = y
self.z = z
class Vector2D:
def __init__(self, x, y) -> None:
self.x = x
self.y = y
class Vector3D:
def __init__(self, x, y, z) -> None:
self.x = x
self.y = y
self.z = z
def test():
points = [
Point2D(0, 1),
Point2D(0, 1),
Point3D(0, 1, 2),
Point3D(0, 1, 3),
Vector2D(0, 1),
Vector3D(0, 1, 4),
]
z_objects = []
# TODO(You): 请在此过滤出含有'z'属性的对象,在过滤中打印出对应对象的'z'属性
for p in z_objects:
print('x+y+z:', p.x+p.y+p.z)
if __name__ == '__main__':
test()
```
请选出下列能**正确**实现这一功能的选项。
## template
```python
class Point2D:
def __init__(self, x, y) -> None:
self.x = x
self.y = y
class Point3D:
def __init__(self, x, y, z) -> None:
self.x = x
self.y = y
self.z = z
class Vector2D:
def __init__(self, x, y) -> None:
self.x = x
self.y = y
class Vector3D:
def __init__(self, x, y, z) -> None:
self.x = x
self.y = y
self.z = z
def test():
points = [
Point2D(0, 1),
Point2D(0, 1),
Point3D(0, 1, 2),
Point3D(0, 1, 3),
Vector2D(0, 1),
Vector3D(0, 1, 4),
]
z_objects = []
for p in points:
if hasattr(p, 'z'):
z = getattr(p, 'z')
print('get z attr:', z)
z_objects.append(p)
for p in z_objects:
print('x+y+z:', p.x+p.y+p.z)
if __name__ == '__main__':
test()
```
## 答案
```python
for p in points:
if hasattr(p, 'z'):
z = getattr(p, 'z')
print('get z attr:', z)
z_objects.append(p)
```
## 选项
### A
```python
for p in points:
z = getattr(p, 'z')
print('get z attr:', z)
z_objects.append(p)
```
### B
```python
for p in points:
if not hasattr(p, 'z'):
z = getattr(p, 'z')
print('get z attr:', z)
z_objects.append(p)
```
### C
```python
for p in points:
if p.hasattr('z'):
z = p.getattr(p, 'z')
print('get z attr:', z)
z_objects.append(p)
```
......@@ -9,5 +9,5 @@ if __name__ == '__main__':
# walker = TreeWalker("data", "python", "python")
# walker.walk()
md = MDWalker('data/1.python初阶/2.基础语法')
md = MDWalker('data/1.python初阶/4.面向对象编程')
md.walk()
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册