问题描述
给定一个复合类型的 Julia 对象,如何确定它的字段?
Given a Julia object of composite type, how can one determine its fields?
如果您在 REPL 中工作,我知道一个解决方案:首先您通过调用 typeof
确定对象的类型,然后进入帮助模式 (?
),然后查找类型.有没有更程序化的方式来实现同样的目标?
I know one solution if you're working in the REPL: First you figure out the type of the object via a call to typeof
, then enter help mode (?
), and then look up the type. Is there a more programmatic way to achieve the same thing?
推荐答案
适用于 v0.7+
使用 fieldnames(x)
,其中 x
是 DataType
.例如,使用 fieldnames(Date)
, 代替 fieldnames(today())
,或者使用 fieldnames(typeof(today()))
.
Use fieldnames(x)
, where x
is a DataType
. For example, use fieldnames(Date)
, instead of fieldnames(today())
, or else use fieldnames(typeof(today()))
.
这将返回 Vector{Symbol}
按顺序列出字段名称.
This returns Vector{Symbol}
listing the field names in order.
如果字段名称是 myfield
,则要检索该字段中的值,请使用 getfield(x, :myfield)
或快捷语法 x.myfield
.
If a field name is myfield
, then to retrieve the values in that field use either getfield(x, :myfield)
, or the shortcut syntax x.myfield
.
另一个有用的相关函数是 dump(x)
.
Another useful and related function to play around with is dump(x)
.
v0.7 之前
使用 fieldnames(x)
,其中 x
是您感兴趣的复合类型的实例,或者是 DataType
.即 fieldnames(today())
和 fieldnames(Date)
同等有效,输出相同.
Use fieldnames(x)
, where x
is either an instance of the composite type you are interested in, or else a DataType
. That is, fieldnames(today())
and fieldnames(Date)
are equally valid and have the same output.
这篇关于如何获取 Julia 对象的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!