问题描述
给出一个复合类型的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对象的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!