Julia 中的抽象类型和继承 [英] Abstract types and inheritance in 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?
这似乎与 Julia#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.)
我认为推荐的实现你正在寻找的方法是沿着这些思路(注意 type
已被弃用并被 struct
取代):
I think the recommended way of implementing what you are looking for is something along these lines (note that type
has been deprecated and replaced by struct
):
abstract type A end
struct B <: A
x
y
end
struct 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屋!