为什么Ruby既有私有方法又有受保护的方法? [英] Why does Ruby have both private and protected methods?
问题描述
Before I read this article, I thought access control in Ruby worked like this:
-
public
-可以被任何对象(例如Obj.new.public_method
)访问 -
protected
-只能从对象本身以及任何子类中访问 -
private
-与protected相同,但是该方法在子类中不存在
public
- can be accessed by any object (e.g.Obj.new.public_method
)protected
- can only be accessed from within the object itself, as well as any subclassesprivate
- same as protected, but the method doesn't exist in subclasses
但是,看来protected
和private
的行为相同,不同的是,您不能使用显式接收器调用private
方法(即self.protected_method
起作用,但self.private_method
不能) t).
However, it appears that protected
and private
act the same, except for the fact that you can't call private
methods with an explicit receiver (i.e. self.protected_method
works, but self.private_method
doesn't).
这有什么意义?什么时候会出现您不希望使用显式接收器调用方法的情况?
What's the point of this? When is there a scenario when you wouldn't want your method called with an explicit receiver?
推荐答案
protected
方法.
private
方法只能在调用对象内调用.您不能直接访问另一个实例的私有方法.
private
methods can be called only from within the calling object. You cannot access another instance's private methods directly.
这是一个快速的实际示例:
Here is a quick practical example:
def compare_to(x)
self.some_method <=> x.some_method
end
此处
some_method
不能为private
.它必须为protected
,因为您需要它来支持显式的接收者.典型的内部帮助器方法通常是private
,因为它们不需要像这样被调用.
some_method
cannot be private
here. It must be protected
because you need it to support explicit receivers. Your typical internal helper methods can usually be private
since they never need to be called like this.
重要的是要注意,这与Java或C ++的工作方式不同. Ruby中的private
与Java/C ++中的protected
相似,因为子类可以访问该方法.在Ruby中,无法像Java中的private
那样,限制从方法的子类访问方法.
It is important to note that this is different from the way Java or C++ works. private
in Ruby is similar to protected
in Java/C++ in that subclasses have access to the method. In Ruby, there is no way to restrict access to a method from its subclasses like you can with private
in Java.
无论如何,Ruby中的可见性在很大程度上都是推荐",因为您始终可以使用send
来访问方法:
Visibility in Ruby is largely a "recommendation" anyways since you can always gain access to a method using send
:
irb(main):001:0> class A
irb(main):002:1> private
irb(main):003:1> def not_so_private_method
irb(main):004:2> puts "Hello World"
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0> foo = A.new
=> #<A:0x31688f>
irb(main):009:0> foo.send :not_so_private_method
Hello World
=> nil
这篇关于为什么Ruby既有私有方法又有受保护的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!