0Pricing
Mojo Academy · 课时

跨桥传递数据

在 Mojo 值和 Python 值之间转换

跨桥传递数据 是 CoddyKit 上的免费 Mojo Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Mojo Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Mojo Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Two Worlds of Values

Mojo has its own native types, and Python has its own. Interop means converting values as they cross between the two worlds.

Mojo to Python

When you pass a Mojo value into a Python call, Mojo automatically wraps it into a PythonObject Python can understand.

var n: Int = 42
print(np.sqrt(n))

Numbers Convert Cleanly

Simple values like Int and Float move across smoothly, becoming Python ints and floats with no extra work from you.

var x: Float64 = 3.5
var r = math.floor(x)

Strings Travel Too

A Mojo String becomes a Python str on the way in, so text-based functions just work across the bridge.

var name = String("Mojo")
print(name)

Python to Mojo

Coming back, Python results arrive as a PythonObject. You then convert it into a native Mojo type when you need one.

var obj = math.factorial(5)

Unwrap to Int

To get a real Mojo number from a result, construct the type from the object, like wrapping it in Int.

var count = Int(math.factorial(5))

Unwrap to Float

The same idea works for decimals: build a Float64 from the Python result to use it in Mojo math.

var ratio = Float64(math.pi)

Unwrap to String

Turn a Python text result into a Mojo String the same way, so you can store and process it natively.

var label = String(obj)

Indexing Python Collections

You can index a Python list or array result with brackets, getting back another PythonObject to convert.

var first = arr[0]

Convert at the Edges

A good habit: keep values as PythonObjects while talking to Python, then convert to Mojo types at the boundary you control.

Why It Matters

Knowing how data crosses the bridge keeps your types predictable, so Python results flow safely into fast Mojo code. 🌉

Quick Check

Recall how to turn a Python result into a Mojo number.

Recap

You saw Mojo values become PythonObjects going in, and learned to convert results back into Int, Float, or String. 🎯

常见问题解答

「跨桥传递数据」课时是免费的吗?

是的 — 「跨桥传递数据」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Mojo Academy 课程的其余内容,请升级到 CoddyKit PRO。 Mojo Academy 课程共包含 4 节课。

「跨桥传递数据」这节课中我会学到什么?

在 Mojo 值和 Python 值之间转换 你通过在浏览器中直接运行的动手代码来练习 Mojo Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Mojo Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Mojo Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「跨桥传递数据」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Mojo Academy 课中编写并运行代码吗?

能。每节 Mojo Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 导入 Python 模块
  2. 调用 Python 函数
  3. 跨桥传递数据
  4. 何时使用 Python 互操作
← 返回 Mojo Academy