gpt4 book ai didi

function - 'def' 和没有 'def' 之间的区别

转载 作者:行者123 更新时间:2023-12-03 03:50:32 29 4
gpt4 key购买 nike

我是一个时髦的初学者。
我很困惑是否使用了“def”。

def str = "hello"
print str

对比
str = "hello"
print str

从这个例子。结果是一样的。但我想知道它们是否不同。
还有其他情况不同吗?

最佳答案

第二个示例仅在您使用脚本时才有效。见 3.2 Script class here .

没有 def 变量存储在脚本的绑定(bind)中,并在该脚本中作为“全局”变量工作。

如果您使用 def 定义变量它将是 Script 的 run 的局部变量方法,并遵循局部变量的所有规则。如果您使用一个脚本,这种差异并不重要。

可以用以下代码段说明差异:

def closureA = { println(a) }
def closureB = { println(b) }

a = "I'm global"
def b = "I'm local"

println(a) // prints "I'm global"
println(b) // prints "I'm local"

closureA() // prints "I'm global"
closureB() // throws groovy.lang.MissingPropertyException: No such property: b

这里我首先声明 2 个闭包(匿名函数)。请注意,在声明时, a也不是 b已声明,因此闭包无法访问。没关系。

然后我调用 println直接在声明之后,在这种情况下,我与 a 处于同一范围内和 b .我能够打印他们的值(value)。

接下来我称之为闭包。两个闭包都检查局部范围,如果在那里找不到变量,它们检查 bindings .这就是区别: a可以访问,而 b - 不是。

关于function - 'def' 和没有 'def' 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35626423/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com