【问题标题】:calling another method in super class in ruby在 ruby​​ 的超类中调用另一个方法
【发布时间】:2010-11-18 01:56:56
【问题描述】:
A级 定义一个 将'放入#a' 结尾 结尾 B类

【问题讨论】:

    标签: ruby


    【解决方案1】:
    class B < A
    
      alias :super_a :a
    
      def a
        b()
      end
      def b
        super_a()
      end
    end  
    

    【讨论】:

    • 要给类方法起别名,请参阅stackoverflow.com/questions/2925016/…
    • 自从写完这个答案后,alias 是否可能已重命名为 alias_method
    • @JaredBeck 它真的被重命名了。所以现在应该是: alias_method :super_a :a
    • 为什么会这样?为什么这不将:super_a 别名为B.a 而是将其别名为A.a
    • @MarkoAvlijaš 在您创建别名时,B.a 尚未定义...如果您将alias 放在def a 下方,情况并非如此
    【解决方案2】:

    没有很好的方法,但你可以使用A.instance_method(:a).bind(self).call,它会起作用,但很难看。

    您甚至可以在 Object 中定义自己的方法,使其像 java 中的 super:

    class SuperProxy
      def initialize(obj)
        @obj = obj
      end
    
      def method_missing(meth, *args, &blk)
        @obj.class.superclass.instance_method(meth).bind(@obj).call(*args, &blk)
      end
    end
    
    class Object
      private
      def sup
        SuperProxy.new(self)
      end
    end
    
    class A
      def a
        puts "In A#a"
      end
    end
    
    class B<A
      def a
      end
    
      def b
        sup.a
      end
    end
    B.new.b # Prints in A#a
    

    【讨论】:

    • @klochner 我不同意,这个解决方案正是我需要的......原因:我想一般地调用不同方法的超级方法,但不需要为我想要的每一个别名能够做到这一点,所以调用 super 的通用方法非常有用
    • 复杂的定义一次,简单的调用很多次。这比反之更好。
    【解决方案3】:

    如果您不明确需要从 B#b 调用 A#a,而是需要从 B#a 调用 A#a,这实际上就是您通过 B#b 执行的操作(除非您'这个例子还不够完整,无法说明为什么你从 B#b 调用,你可以从 B#a 中调用 super,就像有时在初始化方法中所做的那样。我知道这很明显,我只是想向任何 Ruby 新手澄清在每种情况下您都不必使用别名(特别是有时称为“周围别名”)。

    class A
      def a
        # do stuff for A
      end
    end
    
    class B < A
      def a
        # do some stuff specific to B
        super
        # or use super() if you don't want super to pass on any args that method a might have had
        # super/super() can also be called first
        # it should be noted that some design patterns call for avoiding this construct
        # as it creates a tight coupling between the classes.  If you control both
        # classes, it's not as big a deal, but if the superclass is outside your control
        # it could change, w/o you knowing.  This is pretty much composition vs inheritance
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多