Dart 类与对象
系统讲解 Dart 类的定义与实例化、普通/语法糖/命名构造函数、初始化列表与 debug 断言、私有封装、计算属性 Getter/Setter 以及 static 静态成员。
学完这一章,你能够
- 系统讲解 Dart 类的定义与实例化、普通/语法糖/命名构造函数、初始化列表与 debug 断言、私有封装、计算属性 Getter/Setter 以及 static 静态成员。
类的定义、实例化与多种构造函数形态
类是封装状态(成员变量)与行为(成员方法)的蓝图,对象是按该蓝图分配的独立实例。自 Dart 2.0 起,实例化对象时 `new` 关键字已变为可选,现代 Dart 代码一律推荐省略 `new`(如直接写 `var user1 = User();`),不同实例各自维护独立字段副本。
构造函数在对象创建阶段完成状态初始化:若类未显式声明任何构造函数,Dart 会自动合成无参默认构造函数;普通构造函数与类同名并通过 `this.field = param` 赋值;更地道的是使用初始化形参语法糖 `Student(this.name, this.age);`,既简洁又能在进入构造体前直接完成非空与 `final` 字段绑定。
Dart 不支持按参数个数重载同名构造函数,而是提供语义清晰的命名构造函数(如 `Point.origin()`、`Point.diagonal(double value)`),在工程中还常结合 `const` 常量构造与 `factory` 工厂构造灵活控制实例创建。配合冒号引导的初始化列表(Initializer List,如 `: age = 2026 - birthYear, assert(birthYear > 1900, '出生年份不合理')`),可在构造函数体执行之前安全初始化 `final` 字段并执行前置校验;需牢记 `assert` 仅在开发调试模式生效,生产发布构建会将其完全移除。
成员变量封装、Getter/Setter 与静态成员
面向对象封装的核心在于隐藏内部状态并暴露受控操作。例如 `BankAccount` 将 `_accountNumber`、`_balance` 与 `_logTransaction` 以单下划线 `_` 标记为库级私有,外部调用者只能通过公开的 `deposit` 与 `withdraw` 方法在校验金额与余额后更新账户状态,杜绝非法篡改。
Getter(`double get diameter => _radius * 2;`)与 Setter(`set radius(double value) { ... }`)允许以普通属性的访问语法背后挂接计算逻辑与参数合法性校验(例如半径 `<= 0` 时抛出 `ArgumentError`),不配 Setter 即自然形成只读属性。由于外部调用语法与普通字段完全一致,日后将简单字段平滑升级为带校验的属性时不会破坏任何调用方代码。
以 `static` 修饰的类变量(如 `Counter.totalCount`)与类方法(如 `Counter.isValidLabel`)归属于类本身而非单个对象,所有实例共享同一份静态字段,静态方法无需实例化即可通过类名直接调用。静态方法内部不存在 `this`,不可访问实例成员,且无法被子类重写,适合放置纯工具逻辑或实例统计,但不宜滥用以免损害代码可测试性。
离线校验 Dart 命名构造函数、初始化列表断言、Getter/Setter 校验与 static 状态
"""Offline Dart 3.x semantic verification lab for Chapter 10 (classes-and-objects)."""
import json
VERSION = "CPython 3.12.14 offline Dart 3.x semantic verifier (dart SDK absent)"
def case_class_instantiation_and_constructors():
class User:
def __init__(self):
self.name = ""
self.age = 0
def is_adult(self) -> bool:
return self.age >= 18
class Student:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
class Point:
def __init__(self, x: float, y: float):
self.x = float(x)
self.y = float(y)
@classmethod
def origin(cls):
return cls(0.0, 0.0)
@classmethod
def diagonal(cls, value: float):
return cls(value, value)
def __str__(self) -> str:
return f"Point({self.x}, {self.y})"
u1 = User()
u1.name, u1.age = "bluesky", 10
u2 = User()
u2.name, u2.age = "小明", 20
s1 = Student("bluesky", 10)
points = [str(Point(3, 4)), str(Point.origin()), str(Point.diagonal(5))]
expected = {
"u1_adult": False,
"u2_adult": True,
"instances_isolated": True,
"student_info": "bluesky:10",
"points": ["Point(3.0, 4.0)", "Point(0.0, 0.0)", "Point(5.0, 5.0)"],
}
actual = {
"u1_adult": u1.is_adult(),
"u2_adult": u2.is_adult(),
"instances_isolated": u1.name != u2.name,
"student_info": f"{s1.name}:{s1.age}",
"points": points,
}
return {
"name": "class_instantiation_and_constructors",
"summary": "校验对象独立状态、语法糖构造函数及 Point.origin / Point.diagonal 命名构造函数",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_initializer_list_and_assert():
class Person:
def __init__(self, name: str, birth_year: int, *, debug_mode: bool = True):
if debug_mode and not (birth_year > 1900):
raise AssertionError("出生年份不合理")
self.name = name
self.birth_year = birth_year
self.age = 2026 - birth_year
p_ok = Person("bluesky", 2016, debug_mode=True)
debug_caught = False
try:
Person("error", 1800, debug_mode=True)
except AssertionError:
debug_caught = True
p_release = Person("legacy", 1800, debug_mode=False)
expected = {
"computed_age": 10,
"debug_assert_triggered": True,
"release_ignores_assert_age": 226,
}
actual = {
"computed_age": p_ok.age,
"debug_assert_triggered": debug_caught,
"release_ignores_assert_age": p_release.age,
}
return {
"name": "initializer_list_and_assert",
"summary": "校验构造函数初始化列表计算 final 字段及 assert 仅在 debug 模式生效的特性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_encapsulation_getters_and_setters():
class BankAccount:
def __init__(self, owner: str, account_number: str):
self.owner = owner
self._account_number = account_number
self._balance = 0.0
def deposit(self, amount: float):
if amount > 0:
self._balance += amount
def withdraw(self, amount: float) -> bool:
if 0 < amount <= self._balance:
self._balance -= amount
return True
return False
@property
def balance_snapshot(self) -> float:
return self._balance
class Circle:
def __init__(self, radius: float):
self._radius = float(radius)
@property
def diameter(self) -> float:
return self._radius * 2
@property
def area(self) -> float:
return 3.14159 * self._radius * self._radius
@property
def radius(self) -> float:
return self._radius
@radius.setter
def radius(self, value: float):
if value <= 0:
raise ValueError("ArgumentError: 半径必须大于 0")
self._radius = float(value)
acc = BankAccount("BlueSky", "6222-0000-1234")
acc.deposit(1000)
w1 = acc.withdraw(300)
w2 = acc.withdraw(800)
c = Circle(5)
area_5 = f"{c.area:.2f}"
c.radius = 10
diam_10 = c.diameter
invalid_rejected = False
try:
c.radius = -1
except ValueError:
invalid_rejected = True
expected = {
"withdraw_300": True,
"withdraw_800": False,
"final_balance": 700.0,
"circle_area_5": "78.54",
"circle_diameter_10": 20.0,
"negative_radius_rejected": True,
}
actual = {
"withdraw_300": w1,
"withdraw_800": w2,
"final_balance": acc.balance_snapshot,
"circle_area_5": area_5,
"circle_diameter_10": diam_10,
"negative_radius_rejected": invalid_rejected,
}
return {
"name": "encapsulation_getters_and_setters",
"summary": "验证 BankAccount 余额封装保护及 Circle 的计算属性 Getter 与带校验 Setter",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_static_members_shared_state():
class Counter:
total_count = 0
def __init__(self, label: str):
self.label = label
Counter.total_count += 1
@staticmethod
def is_valid_label(label: str) -> bool:
return len(label) > 0 and len(label) <= 20
valid_before_inst = Counter.is_valid_label("test")
invalid_empty = Counter.is_valid_label("")
_c1 = Counter("A")
after_1 = Counter.total_count
_c2, _c3 = Counter("B"), Counter("C")
after_3 = Counter.total_count
expected = {
"valid_label_without_instance": True,
"empty_label_valid": False,
"count_after_1": 1,
"count_after_3": 3,
}
actual = {
"valid_label_without_instance": valid_before_inst,
"empty_label_valid": invalid_empty,
"count_after_1": after_1,
"count_after_3": after_3,
}
return {
"name": "static_members_shared_state",
"summary": "校验 static 类级共享状态与无需实例化的静态工具方法行为",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_class_instantiation_and_constructors(),
case_initializer_list_and_assert(),
case_encapsulation_getters_and_setters(),
case_static_members_shared_state(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 离线脚本验证对象状态隔离、Point 命名构造、debug/release 模式 assert 行为差异、BankAccount 与 Circle 校验封装及 Counter 静态共享计数。
所需环境:Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。
当前源码 SHA256:dcab0dbf5463aaebbcdf9271298283b1bfa8a84ba46e2bb49adac3532e10184e
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。
ZIP SHA256:f2da283cb2789ab1907f3226ea7ceaff5182edc0d15743931053b3ab210f6ab8
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在类的构造函数中,为什么必须在初始化列表(`: field = ...`)而非构造函数体 `{ ... }` 内为 `final` 字段赋值?
展开参考解答
初始化列表在构造函数体执行之前运行,能够确保在对象对外暴露及 `this` 可访问之前所有非空与 `final` 字段均已完成唯一一次初始化;进入构造函数体时 `final` 字段已锁定不可再写入。