【问题标题】:Python Mixins: *args/**kwargs vs explicit call to `__init__`Python Mixins:*args/**kwargs 与显式调用`__init__`
【发布时间】:2020-10-18 19:25:23
【问题描述】:

我尝试编写一个使用 ClickableRectangle 类的 Mixins 示例,它们是 Button 类的超类。

目前我使用:

class Clickable:
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.clicks = 0

    def click(self):
        self.clicks = self.clicks + 1


class Rectangle:
    def __init__(self, x0, y0, x1, y1, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.upper_right = (x0, y0)
        self.lower_down = (x1, y1)


class Button(Clickable, Rectangle):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

但我考虑使用:

class Clickable:
    def __init__(self):
        self.clicks = 0

    def click(self):
        self.clicks = self.clicks + 1


class Rectangle:
    def __init__(self, x0, y0, x1, y1):
        self.upper_right = (x0, y0)
        self.lower_down = (x1, y1)


class Button(Clickable, Rectangle):
    def __init__(self, x0, y0, x1, y1):
        Rectangle.__init__(self, x0, y0, x1, y1)
        Clickable.__init__(self)

由于某种原因,其中一个更好吗?

【问题讨论】:

    标签: python python-3.x inheritance multiple-inheritance mixins


    【解决方案1】:

    推荐的方法(参见https://rhettinger.wordpress.com/2011/05/26/super-considered-super/)是使用关键字参数来避免预期传递哪个父级参数和位置参数之间的冲突。

    class Clickable:
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
            self.clicks = 0
    
        def click(self):
            self.clicks = self.clicks + 1
    
    
    class Rectangle:
        def __init__(self, x0, y0, x1, y1, **kwargs):
            super().__init__(**kwargs)
            self.upper_right = (x0, y0)
            self.lower_down = (x1, y1)
    
    
    class Button(Clickable, Rectangle):
        # No need to override __init__ if all it does
        # is pass all its arguments to the next invocation
        pass
    
    
    b = Button(x0=0, y0=0, x1=10, y1=10)
    

    请记住,接受任意关键字参数并首先传递它们的原因是您不知道super() 会生成哪个类,因此您无法预测预期的签名。

    根据定义,Mixin 几乎可以支持协作继承,因为它们预计将与多重继承一起使用,并且有人可能希望在支持的类中使用您的 mixin。 p>

    【讨论】:

      猜你喜欢
      • 2017-04-07
      • 2021-11-26
      • 2013-11-13
      • 2017-03-26
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      相关资源
      最近更新 更多