相关疑难解决方法(0)

什么是mixin,为什么它们有用?

在" 编程Python "中,Mark Lutz提到了"mixins".我来自C/C++/C#背景,我之前没有听过这个词.什么是mixin?

这个例子的行之间进行读取(我已经链接到了因为它很长),我假设这是一个使用多重继承来扩展类而不是"正确"子类的情况.这是正确的吗?

为什么我要这样做而不是将新功能放入子类?就此而言,为什么mixin/multiple继承方法比使用组合更好?

mixin与多重继承的区别是什么?这仅仅是语义问题吗?

python oop multiple-inheritance mixins

875
推荐指数
16
解决办法
27万
查看次数

在Mixins中初始化实例变量

是否有任何干净的方法来初始化模块中的实例变量以用作Mixin?例如,我有以下内容:

module Example

  def on(...)   
    @handlers ||= {} 
    # do something with @handlers
  end

  def all(...)
    @all_handlers ||= []
    # do something with @all_handlers
  end

  def unhandled(...)
    @unhandled ||= []
    # do something with unhandled
  end

  def do_something(..)
    @handlers     ||= {}
    @unhandled    ||= []
    @all_handlers ||= []

    # potentially do something with any of the 3 above
  end

end
Run Code Online (Sandbox Code Playgroud)

请注意,我必须反复检查@member每个功能是否已在每个功能中正确初始化 - 这有点刺激性.我宁愿写:

module Example

  def initialize
    @handlers     = {}
    @unhandled    = []
    @all_handlers = []
  end

  # or …
Run Code Online (Sandbox Code Playgroud)

ruby mixins

11
推荐指数
1
解决办法
7617
查看次数

标签 统计

mixins ×2

multiple-inheritance ×1

oop ×1

python ×1

ruby ×1