gpt4 book ai didi

ruby - 使用私有(private) attr_accessor 时,为什么 self.attribute= 起作用,而 self.attribute 不起作用?

转载 作者:数据小太阳 更新时间:2023-10-29 08:02:36 27 4
gpt4 key购买 nike

假设我有一个类,我在其中定义了一个 attr_accessor,如下所示:

private

attr_accessor :attribute

我理解为什么使用 self.attribute 读取器方法不起作用 - 在 Ruby 中,您不能在显式接收器上调用私有(private)方法。

令我困惑的是,为什么这条规则不适用于作者?为什么我可以调用 self.attribute = 1,并且不会引发任何访问冲突错误?

最佳答案

根据@Jörg W Mittag 对 Alan Skorkin 博客条目的评论 Ruby Access Control – Are Private And Protected Methods Only A Guideline? :

Quick note: there is a special case where calling private methods with an explicit receiver is allowed:

If the method name ends with '=' (i.e. it is an attribute writer) and the explicit receiver is 'self', then this works. This is necessary, because setters can only be called with an explicit receiver because of the method/variable ambiguity. Otherwise it wouldn't be possible to call private setters.

Jörg 没有引用任何消息来源,但他非常可靠。

关于ruby - 使用私有(private) attr_accessor 时,为什么 self.attribute= 起作用,而 self.attribute 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45701663/

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