【问题标题】:Including a module from within another module in Julia在 Julia 的另一个模块中包含一个模块
【发布时间】:2020-04-17 01:21:05
【问题描述】:

我在文件中定义了一个模块。这个 Module1 定义了我在主脚本中使用的结构和函数。我使用 include("module1.jl") 将此模块包含在另一个父模块中,以便父模块可以使用模块 1 中的结构和函数。但是,我遇到了命名空间的问题。这是单个文件中的示例:

#this would be the content of module.jl
module Module1
    struct StructMod1
    end
    export StructMod1
    function fit(s::StructMod1)
    end
    export fit
end

module Parent
    #including the module with include("Module1.jl")
    module Module1
        struct StructMod1
        end
        export StructMod1
        function fit(s::StructMod1)
        end
        export fit
    end
    #including the exports from the module
    using .Module1
    function test(s::StructMod1)
        fit(s)
    end
    export test
end

using .Parent, .Module1

s = StructMod1
test(s)



ERROR: LoadError: MethodError: no method matching test(::Type{StructMod1})
Closest candidates are:
  test(::Main.Parent.Module1.StructMod1)

如果我删除 Parent 中的模式包含并使用 Using ..Module1 以便它从封闭范围加载,我会收到此错误

ERROR: LoadError: MethodError: no method matching test(::Type{StructMod1})

    Closest candidates are:
      test(::StructMod1) at ...

【问题讨论】:

  • 什么时候报错,是加载模块还是调用函数test的时候?
  • 调用测试时会发生两个错误
  • 大卫在下面回答::Type{StructMod1} 表示您传递了一个类型,而不是一个实例。一个实例是::StructMod1。错误消息只是说没有test 的方法可以接受Type 类型的参数
  • 是的!那是一个错字。我的问题是使用 StructMod1() 定义结构,然后从另一个模块中调用 fit 函数。我将用更清晰的代码打开一个新问题。顺便说一句,Hyperopt 软件包做得很好!它在我的模拟中非常有用

标签: module namespaces julia


【解决方案1】:

在您的示例中,s 是类型对象,而不是 StructMod1 类型的对象。为了使s 成为后者,您需要调用该类型的构造函数。所以你应该写s = StructMod1()而不是s = StructMod1

您可以阅读更多关于类型作为第一类对象的信息here

【讨论】:

  • 糟糕,这是一个错字。我的代码中仍然存在同样的问题,我将使用更好的示例打开一个新问题。
猜你喜欢
  • 2020-04-17
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
  • 2011-06-03
  • 2016-12-29
  • 2020-06-22
相关资源
最近更新 更多