gpt4 book ai didi

ruby - 为什么私有(private) setter 的行为与其他私有(private)方法不同?

转载 作者:数据小太阳 更新时间:2023-10-29 06:59:33 24 4
gpt4 key购买 nike

这是一个我似乎无法解释的有趣案例。看起来私有(private) setter 是“有点”私有(private)的,但有时也有异常(exception)。常规的私有(private)方法似乎与私有(private) setter 的行为不同:

class TestClass
def do
self.foo = :bar # fine
self.baz # error
end

private

def foo=(other)
@foo = other
end

def baz
end
end

TestClass.new.do

尽管在显式self 上被调用,但上面的代码设置@foo 很好。然后调用#baz失败,因为#baz是私有(private)方法。

这是怎么回事?

最佳答案

私有(private) setter 是特殊的,否则它们根本无法被调用:

foo = :bar

分配给局部变量 foo , 它不发送消息 foo= .

请注意,如果没有明确的接收者, setter 并不是唯一不能调用的东西。 +@ , -@ , ! , ~ , [] , []= , + , - , * , / , % , & , | , ^ , ** , << , >> , == , === , =~ , !~ , != , < , > , <= , >= , <=>如果没有明确的接收者,可能还有一些我忘记的其他人也无法调用。然后是类似 += 的东西, <<=等等。

所有这些都需要有异常(exception)。不幸的是,其中一些只有异常(exception)。

已提议更改 private 的规则来自

Can only be called without an explicit receiver, except for [this long list of exceptions which is really complicated, and still not complete].

Can only be called without an explicit receiver or the literal special variable self as receiver.

它保留了定义的所有当前属性(最重要的是它可以在解析时静态确定)。

But so far, nothing has come of it.

关于ruby - 为什么私有(private) setter 的行为与其他私有(private)方法不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42931949/

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