Julia 如何使类型属性成为其他类型属性的函数?

Julia 如何使类型属性成为其他类型属性的函数?,julia,Julia,要声明新的复合类型,我们使用以下语法 type foo a::Int64 b::Int64 end 并像这样实例化 x = foo(1,3) 是否有某种方法可以使类型属性始终只是其他属性的函数?例如,是否有某种方法可以执行以下操作(这是无效语法) 我目前的解决方法只是定义一个计算c并返回该类型实例的函数,如下所示 type foo a::Int64 b::Int64 c::Int64 end function foo_maker(a, b)

要声明新的复合类型,我们使用以下语法

type foo
    a::Int64
    b::Int64
end
并像这样实例化

x = foo(1,3)
是否有某种方法可以使类型属性始终只是其他属性的函数?例如,是否有某种方法可以执行以下操作(这是无效语法)

我目前的解决方法只是定义一个计算c并返回该类型实例的函数,如下所示

type foo
    a::Int64
    b::Int64
    c::Int64
end

function foo_maker(a, b)
    return foo(a, b, a+b)
end
有更优雅的解决方案吗?可能是一个可以包含在类型定义中的

编辑-3/7/14

考虑到Cristóvão的建议,我最终声明了如下构造函数,以允许在实例化时计算关键字arg和属性

# Type with optional keyword argument structure
type LargeType

    # Declare all the attributes in order up top
    q::Int64
    w::Int64
    e::Int64
    r::Int64
    t::Int64
    y::Int64
    a::Number
    b::Number
    c::Number

    # Declare Longer constructor with stuff going on in the body
    LargeType(;q=1,w=1,e=1,r=1,t=1,y=1) = begin 
        # Large Constructor Example 
        a = round(r^t - log(pi))
        b = a % t
        c = a*b
        # Return new instance with correctly ordered arguments
        return new(q,w,e,r,t,y,a,b,c)
    end

end


println(LargeType(r=2,t=5))

目前没有办法做到这一点,但将来可能会有:

试试这个:

julia> type foo
           a::Int64
           b::Int64
           c::Int64
           foo(a::Int64, b::Int64) = new(a, b, a+b)
       end

julia> foo(1,2)
foo(1,2,3)

julia> foo(4,5,6)
no method foo(Int64, Int64, Int64)
但是,这不会阻止手动更改a、b或c并使c不一致。为了防止出现这种情况,如果没有其他问题,可以使foo不可变:

julia> immutable foo
           ...

谢谢你的建议,其实我也试过类似的方法。我在初始类型声明之外定义了新的构造函数
foo(a::Int64,b::Int64)=foo(a,b,a+b)
把它放在里面有好处吗?我的理解是,使用
new
将类型限制为仅限于该构造函数,这是优点之一。在这里见其他人。
julia> immutable foo
           ...