"""蓝色天空网 mbsky.com · 内置函数、迭代器和输入输出实验。"""
from contextlib import redirect_stdout
import importlib
from io import StringIO
from pathlib import Path
import platform
import sys
from tempfile import TemporaryDirectory
from types import SimpleNamespace
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
COURSE = "Python3"
class Product:
def __init__(self, price):
self._price = price
@property
def price(self):
return self._price
@classmethod
def label(cls):
return cls.__name__
@staticmethod
def code(text):
return text.upper()
def display(self):
return "商品"
class SaleProduct(Product):
def display(self):
return super().display() + "(促销)"
class BrokenProperty:
@property
def status(self):
raise RuntimeError("无法读取库存状态")
def numbers(check):
check.eq("abs", (abs(-7), abs(3 + 4j)), (7, 5.0))
check.eq("round", (round(2.5), round(3.5), round(2.675, 2)), (2, 4, 2.67))
check.eq("min", (min([], default=0), min(["cat", "a"], key=len)), (0, "a"))
check.raises("min without default rejects empty", ValueError, lambda: min([]))
check.eq("max", (max([8, 3, 5]), max(["a", "cat"], key=len)), (8, "cat"))
check.eq("sum", (sum([4, 2, 6]), sum([4, 2, 6], start=10)), (12, 22))
check.eq("divmod", divmod(-7, 3), (-3, 2))
check.eq("pow", (pow(3, 3), pow(3, 3, 5)), (27, 2))
check.eq("int", (int("42"), int("2a", 16), int(-2.9)), (42, 42, -2))
check.raises("int rejects invalid text", ValueError, lambda: int("three"))
check.eq("float", float("12.5"), 12.5)
check.eq("complex", complex("3-2j"), 3 - 2j)
check.eq("bin", bin(-5), "-0b101")
check.eq("oct", oct(9), "0o11")
check.eq("hex", hex(31), "0x1f")
check.eq("bool", (bool([]), bool([0])), (False, True))
check.eq("all", (all([]), all([1, 0])), (True, False))
check.eq("any", (any([]), any([0, 1])), (False, True))
def sequences(check):
labels = ["B2", "A1"]
check.eq("list", list(iter(labels)), labels)
check.eq("tuple", tuple(labels), ("B2", "A1"))
check.eq("dict", dict([("B2", 3), ("B2", 5)], A1=2), {"B2": 5, "A1": 2})
check.eq("set", set(["B2", "A1", "B2"]), {"A1", "B2"})
check.eq("frozenset", {frozenset(labels): 2}[frozenset(reversed(labels))], 2)
check.eq("range", list(range(5, 0, -2)), [5, 3, 1])
check.raises("range rejects zero step", ValueError, lambda: range(0, 4, 0))
check.eq("slice", labels[slice(0, 2, 2)], ["B2"])
check.eq("reversed", list(reversed(labels)), ["A1", "B2"])
check.eq("sorted", sorted(["B2", "A1", "B1"], key=lambda x: x[0]), ["A1", "B2", "B1"])
check.eq("enumerate", list(enumerate(labels, start=7)), [(7, "B2"), (8, "A1")])
effects = []
def add_stock(stock):
effects.append(stock)
return stock + 2
result = map(add_stock, [4, 2, 6])
check.eq("map is lazy before consumption", effects, [])
check.eq("map", list(result), [6, 4, 8])
check.eq("map is consumed once", (effects, list(result)), ([4, 2, 6], []))
check.eq("filter", list(filter(None, [0, 5, "", 2])), [5, 2])
check.eq("zip", list(zip(labels, [4])), [("B2", 4)])
check.raises("strict zip checks lengths on consumption", ValueError,
lambda: list(zip(labels, [4], strict=True)))
values = iter([4, 2, 0, 8])
check.eq("iter", list(iter(lambda: next(values), 0)), [4, 2])
check.eq("next", (next(values), next(values, None)), (8, None))
check.raises("next raises when exhausted", StopIteration, lambda: next(values))
def objects(check):
item = SaleProduct(29)
check.eq("type", (type(item).__name__, type("Shelf", (), {"size": 3}).size),
("SaleProduct", 3))
check.eq("isinstance", isinstance(item, Product), True)
check.eq("issubclass", issubclass(SaleProduct, Product), True)
check.eq("property", item.price, 29)
check.raises("read only property cannot be assigned", AttributeError,
lambda: setattr(item, "price", 10))
check.eq("classmethod", item.label(), "SaleProduct")
check.eq("staticmethod", (item.code("b2"), Product.code("a1")), ("B2", "A1"))
check.eq("super", item.display(), "商品(促销)")
stock = SimpleNamespace()
check.eq("getattr", getattr(stock, "on_hand", 0), 0)
check.eq("setattr", (setattr(stock, "on_hand", 4), stock.on_hand), (None, 4))
check.eq("vars", vars(stock), {"on_hand": 4})
check.eq("dir", "on_hand" in dir(stock), True)
check.eq("delattr", (delattr(stock, "on_hand"), hasattr(stock, "on_hand")), (None, False))
check.eq("hasattr", hasattr(item, "price"), True)
check.raises("hasattr propagates unrelated exceptions", RuntimeError,
lambda: hasattr(BrokenProperty(), "status"))
check.eq("callable", (callable(item.code), callable(item)), (True, False))
a, b = object(), object()
check.eq("object", (a is b, hasattr(a, "__dict__")), (False, False))
check.eq("id", (id(a) == id(a), id(a) == id(b)), (True, False))
check.eq("hash", hash(True) == hash(1), True)
check.raises("mutable list is unhashable", TypeError, lambda: hash([]))
check.eq("globals", globals()["COURSE"], "Python3")
check.eq("locals", locals()["item"].price, 29)
def text_and_io(check):
check.eq("str", (str(29), str(b"B2", "ascii")), ("29", "B2"))
check.eq("repr", repr("北岸"), "'北岸'")
check.eq("ascii", ascii("北岸"), "'\\u5317\\u5cb8'")
check.eq("format", format(3.25, ".1f"), "3.2")
check.eq("len", len("北岸"), 2)
check.eq("chr", chr(0x5317), "北")
check.eq("ord", ord("北"), 0x5317)
check.raises("chr rejects invalid code point", ValueError, lambda: chr(0x110000))
check.eq("bytes", bytes("北", "utf-8"), b"\xe5\x8c\x97")
mutable = bytearray(b"A2")
mutable[0] = ord("B")
check.eq("bytearray", mutable, bytearray(b"B2"))
with memoryview(mutable) as view:
view[1] = ord("3")
check.eq("memoryview", bytes(mutable), b"B3")
with StringIO() as output:
check.eq("print", (print("B2", 4, sep="=", end="!", file=output), output.getvalue()),
(None, "B2=4!"))
with patch.object(sys, "stdin", StringIO(" 42 \n")), redirect_stdout(StringIO()) as output:
check.eq("input", (input("库存> "), output.getvalue()), (" 42 ", "库存> "))
check.raises("input raises at EOF", EOFError, input)
with TemporaryDirectory(prefix="mbsky-builtins-") as temp:
file = Path(temp) / "stock.txt"
with open(file, "w", encoding="utf-8", newline="\n") as stream:
stream.write("北岸\n")
with open(file, "r", encoding="utf-8") as stream:
text = stream.read()
with open(file, "rb") as stream:
raw = stream.read()
check.eq("open", (text, raw), ("北岸\n", "北岸\n".encode("utf-8")))
with redirect_stdout(StringIO()) as output:
help(str.upper)
help_text = output.getvalue()
check.eq("help", ("upper" in help_text, "uppercase" in help_text), (True, True))
def code_and_modules(check):
scope = {"__builtins__": {}, "stock": 4}
compiled = compile("stock + 3", "<mbsky-expression>", "eval")
check.eq("compile", (type(compiled).__name__, compiled.co_filename), ("code", "<mbsky-expression>"))
check.raises("compile rejects statement in eval mode", SyntaxError,
lambda: compile("stock = 8", "<mbsky-expression>", "eval"))
check.eq("eval", eval(compiled, scope), 7)
check.eq("exec", (exec("stock *= 2", scope), scope["stock"]), (None, 8))
check.eq("__import__", __import__("math").isqrt(81), 9)
check.eq("reload is not a Python 3 builtin", hasattr(__import__("builtins"), "reload"), False)
with TemporaryDirectory(prefix="mbsky-reload-") as temp:
name = "_mbsky_stock_reload_example"
file = Path(temp) / (name + ".py")
file.write_text("stock = 3\n", encoding="utf-8")
sys.path.insert(0, temp)
try:
module = importlib.import_module(name)
previous = module.stock
file.write_text("stock = 42\n", encoding="utf-8")
updated = importlib.reload(module)
check.eq("reload", (updated is module, updated.stock, previous), (True, 42, 3))
finally:
sys.path.remove(temp)
sys.modules.pop(name, None)
def main():
check = Checks()
numbers(check)
sequences(check)
objects(check)
text_and_io(check)
code_and_modules(check)
check.finish("python3-built-in-functions", python=platform.python_version(),
platform=platform.platform(), implementation=platform.python_implementation(),
conditions="Owned fixed expressions, StringIO, isolated temporary directory and module",
source_requests=0)
if __name__ == "__main__":
main()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 环境
入口文件:projects/python-lab/python3-built-in-functions.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python3-built-in-functions.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 环境。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip