Julia中的抽象类型和继承 [英] Abstract types and inheritance in Julia

查看:795
本文介绍了Julia中的抽象类型和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在Julia中的抽象类型A上定义了一个函数:

Suppose I define a function on an abstract type A in Julia:

abstract A
function mysum(a::A)
  a.x + a.y
end

隐式任何子类型都应该有字段x和y使此功能起作用。因此,在A上定义的函数是为子类型设置的要求。这些功能可以在任何地方编写,人们可以想象这样的情况,即功能要复杂得多,而且要求更难以发现。 是否有某种方式声明要求抽象类型的子类型必须具有除函数之外的其他内容?

Implicitly any subtype should have the fields x and y for this function to work. So the functions defined on A are what set the requirements for subtypes. These functions could be written anywhere and one can imagine a situation where the functions are much more complex and the requirements are harder to spot. Is there someway to declare the requirements a subtype of an abstract type must have besides just implicitly from functions?

这似乎与< a href =https://github.com/JuliaLang/julia/issues/6975title =Julia#6975>朱莉娅#6975 但如果与此无关,可能会有人澄清差异。

This seems to be related to Julia#6975 but if its not related to that could someone clarify the difference.

最后,为什么有人想要使用类型联合而不是抽象类型。抽象类型更灵活,可扩展,类型联合是固定。例如

Finally, why would anyone want to use a type union instead of an abstract type. The abstract type is more flexible and extensible, the type union is fixed. For example

为什么:

type A
  x
end

type B
  x
end

typealias C Union{A,B}

而不是:

abstract C

type A <: C
  x
end

type B <: C
  x
end


推荐答案

第一个问题:我认为目前没有办法实现这一目标,但它是关于在语言中添加特征的讨论的核心。你已经发现了一个讨论这个问题的问题,我相信这是1.0版以外的非正式路线图(至少我已经看过它了。)

First question: I do not think there is a way to achieve this currently, but it is at the heart of the discussions about adding traits to the language. You have already found one issue discussing this, and I believe it is on the informal roadmap beyond version 1.0 (at least I've seen it mentioned.)

我认为推荐的实现所需内容的方法是这样的:

I think the recommended way of implementing what you are looking for is something along these lines:

abstract A

type B <: A
    x
    y
end

type C <: A
    w
    z
end

prop1(b::B) = b.x
prop2(b::B) = b.y
prop1(c::C) = c.w
prop2(c::C) = c.z  # changed from prop2(c::C)=c.w

mysum(a::A) = prop1(a) + prop2(a)

也就是说,而不是要求 B C 要拥有相同的字段,您可以实现定义其行为的方法。然后实际的字段名称仍然是每个具体类型的内部实现细节。

That is, instead of requiring B and C to have the same fields, you implement methods that define their behaviour. Then the actual field names remain internal implementation details of each concrete type.

对于联合类型,可以使用它们(除其他外)将方法添加到类型没有共同的超类型。抽象类型很好,但是你不能总是将所有类型都塞进一个公共层次结构中,并且经常你会将方法添加到你自己没有定义的类型集合中。

As for union types, they can be used (among other things) to add methods to types that do not have a common supertype. Abstract types are fine, but you cannot always shoehorn all your types into a common hierarchy, and frequently you will add methods to collections of types that you did not define yourself.

这篇关于Julia中的抽象类型和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆