Jaf*_*rov 5 python import module julia
在 Julia 中,可以导出模块的函数(或变量、结构等),然后可以在另一个脚本中调用它而无需命名空间(一旦导入)。例如:
# helpers.jl
module helpers
function ordinary_function()
# bla bla bla
end
function exported_function()
# bla bla bla
end
export exported_function()
end
Run Code Online (Sandbox Code Playgroud)
# main.jl
include("helpers.jl")
using .helpers
#we have to call the non-exported function with namespace
helpers.ordinary_function()
#but we can call the exported function without namespace
exported_function()
Run Code Online (Sandbox Code Playgroud)
Python 中有这个功能吗?
在 Python 中导入比这更容易:
# module.py
def foo(): pass
# file.py
from module import foo
foo()
# file2.py
from file import foo
foo()
Run Code Online (Sandbox Code Playgroud)
这也适用于classes。
在Python中你还可以做这样的事情:
import module
# You have to call like this:
module.foo()
Run Code Online (Sandbox Code Playgroud)
当您导入模块时,该模块导入的所有函数都被视为该模块的一部分。使用下面的例子:
# file.py
import module
# file2.py
import file
file.module.foo()
# or...
from file import module
module.foo()
# ...or...
from file.module import foo
foo()
Run Code Online (Sandbox Code Playgroud)
请注意,在 Python 中export不需要。
查看: Python 中documentation不存在关键字。export
在 Julia 中,两个模块可以具有export相同的功能,并且 Julia 会自动检测此类问题,即即使您使用export它们,它们也不会相互覆盖:
julia> module A
export x
x() = "a"
end
Main.A
julia> module B
export x
x() = "b"
end
Main.B
julia> using .A, .B
julia> x()
WARNING: both B and A export "x"; uses of it in module Main must be qualified
Run Code Online (Sandbox Code Playgroud)
这就是为什么 Julia 的常见做法是using不这样做import。
在 Python 中,在生产代码中进行等效操作被认为是一种不好的做法。
作为旁注:Julia 和 Python 之间的另一个相关区别是,在 Julia 中,module概念与文件/目录结构分离。您可以在一个文件中包含多个模块,也可以将多个文件组成一个模块。