奇怪的 SimpleDelegator 行为

Kur*_*aga 5 ruby delegation

有我的代码使用SimpleDelegator

require 'delegate'

class Foo < SimpleDelegator
  def meth
    p 'new_meth'
  end
end

class Bar
  def meth
    p 'old_meth'
  end

  def bar_meth
    meth
  end
end

bar = Bar.new
foo = Foo.new(bar)
foo.meth      #=> "new_meth"
foo.bar_meth  #=> "old_meth"
Run Code Online (Sandbox Code Playgroud)

为什么最后一行给出"old_meth"???!!!谢谢!

Aru*_*hit 4

Delegator说:

该库提供了三种不同的方法来将方法调用委托给对象。最容易使用的是SimpleDelegator将一个对象传递给构造函数,该对象支持的所有方法都将被委托。该对象可以稍后更改。

好的,现在看一下输出,它位于符号的右侧# =>

require 'delegate'

class Foo < SimpleDelegator
  def meth
    p 'new_meth'
  end
end

class Bar
  def meth
    p 'old_meth'
  end

  def bar_meth
    self.method(:meth)
  end
end

bar = Bar.new # => #<Bar:0x8b31728>
foo = Foo.new(bar)
foo.__getobj__ # => #<Bar:0x8b31728>
foo.bar_meth # => #<Method: Bar#meth>
foo.method(:meth) # => #<Method: Foo#meth>
Run Code Online (Sandbox Code Playgroud)

因此,当我使用该行时foo.method(:meth),然后输出(#<Method: Foo#meth>)确认每当您调用时foo.meth,都会调用meth该类的方法。但是该行输出()只是说在方法内部,如果您调用方法,则将被调用。Foofoo.bar_meth#<Method: Bar#meth>bar_methmethBar#meth

SimpleDelegator说:

Delegator 的具体实现,此类提供了将所有支持的方法调用委托给传递给构造函数的对象的方法,甚至可以在稍后使用 # setobj更改委托的对象。

是的,在您的情况下,foo对象已bar通过使用设置为对象#__setobj__。该行的输出foo.__getobj__表明了这一点。