检查是否在 Julia 中定义了对象或变量 – isdefined() 和 @isdefined() 方法
isdefined()
是 julia 中的一个内置函数,用于测试指定的全局变量或对象字段是否已定义。传递的参数可以是模块和符号或复合对象和字段名称(作为符号)或索引。
Syntax:
isdefined(m::Module, s::Symbol)
or
isdefined(object, s::Symbol)
or
isdefined(object, index::Int)
Parameters:
- m::Module: Specified module.
- s::Symbol: Specified symbol.
- object: Specified composite object.
- index::Int: Specified index.
Returns: It returns true for the defined specified global variable or object field else returns false.
例子:
# Julia program to illustrate
# the use of isdefined() method
# Getting true for the defined
# specified global variable or
# object field else returns false.
println(isdefined(Base, :sum))
println(isdefined(Base, :num))
println(isdefined(Base, :NonExistentMethod))
# Initialising a composite type value with
# Floor division operator
a = 2//3;
println(isdefined(a, 1))
println(isdefined(a, 2))
println(isdefined(a, :num))
println(isdefined(a, :numerator))
输出:
true
true
false
true
true
true
false
@被定义为()
@isdefined()
是 julia 中的一个内置函数,用于测试指定变量 s 是否定义在当前范围内。
Syntax:
@isdefined s
Parameters:
- s: Specified variable.
Returns: It returns true if the specified variable s is defined in the current scope else returns false.
例子:
# Julia program to illustrate
# the use of @isdefined() method
# Getting true if the specified variable
# s is defined in the current scope
# else returns false.
function f()
println(@isdefined x)
x = 10
println(@isdefined x)
end
f (generic function with 1 method)
println(f())
输出: