从结构体到实例
Coddy 面向 Rust 开发者的 Python 课程的第 32 课,共 48 课。
Rust 结构体会声明其字段,并使用 impl 块定义行为。基本的 Python 类可以从空类开始,普通实例也可以在运行时接收属性。类的创建和实例的创建是不同的:调用 Parcel() 会创建一个实例。使用点号访问属性。这种灵活性并不意味着每个 Python 对象都允许任意添加属性;使用 slots 的类和许多内置类型会限制这类操作。最好始终一致地初始化预期状态,而不是依赖零散的后续赋值。
main 中的 Rust 代码片段
struct Parcel { label: String, weight: i32 }
let parcel = Parcel { label: String::from("sample"), weight: 4 };
println!("{}", parcel.label);
assert_eq!(parcel.weight, 4);Python
class Parcel:
pass
parcel = Parcel()
parcel.label = "sample"
parcel.weight = 4
print(parcel.label)移植时容易踩的坑
Rust 字段的可见性由编译器强制执行。Python 中,名称以下划线开头只是一种约定,表示调用者应将该属性视为内部属性,但这并不能强制实现模块级隐私。
在可编辑的 Python 文件中实现指定的 API。锁定的 driver.py 会运行程序并提供输入和输出。保持其中的导入项和名称不变。
挑战
入门使用 pass 作为类体,定义一个空的 Parcel 类。定义 make_parcel(label, weight),用于创建一个新的 Parcel(),为其赋值实例属性 label 和 weight,然后返回它。输入有 5 行:第一个标签、第一个整数重量、第二个标签、第二个整数重量,以及一个整数增量。标签可以为空;重量和增量均为非负数。驱动程序只增加第一个包裹的重量,然后将每个包裹打印为 label:weight,接着打印这两个包裹是否相同(True 或 False)。
锁定的驱动程序会读取输入并打印结果。只提交所需的类和函数定义,不要在你的答案中读取输入或打印内容。API 名称必须与指定名称完全一致。
你的代码应写在可编辑文件 parcel.py 和 functions.py 中。driver.py 包含提供的输入输出代码和 API 检查,不能编辑。保留提供的导入语句;不要在可编辑模块中读取输入或打印内容。
亲手试试
from parcel import Parcel
from functions import make_parcel
a = make_parcel(input(), int(input()))
b = make_parcel(input(), int(input()))
assert isinstance(a, Parcel) and isinstance(b, Parcel)
a.weight += int(input())
print(f"{a.label}:{a.weight}")
print(f"{b.label}:{b.weight}")
print(a is b)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Rust 开发者的 Python中的所有课
自己练习: Python 在线编译器