【问题标题】:Trouble deciding what and how to inherit难以决定继承什么以及如何继承
【发布时间】:2020-01-17 20:38:52
【问题描述】:

我的父类中有一个构造函数,它接受四个参数。在我的子类中,我需要一个带有三个参数的类。在父类 I 中,第一个参数是长度。子类将有一个固定的长度。

我尝试了很多东西,但没有一个奏效。我添加的代码中的一个就是其中之一。

    class X:
        def __init__(self, len, speed, locate, direction):
        self._len = len
        self._speed = speed
        self._locate = locate
        self._direction = direction

    from X import X

    class Y(X):
        def __int__(self, speed, locate, direction):
            super().__init__(speed, locate, direction)
            # one thing I've tried
            self._len = 3.0

当我创建一个对象并尝试在其中传递三个参数时,表示我缺少方向。

【问题讨论】:

    标签: python-3.x superclass


    【解决方案1】:

    只需将 *args**kwargs 传递给您的两个类初始化:

    class X:
        def __init__(self, len, speed, locate, direction, *args, **kwargs):
        self._len = len
        self._speed = speed
        self._locate = locate
        self._direction = direction
    
    from X import X
    
    class Y(X):
        def __int__(self, speed, locate, direction, *args, **kwargs):
            super().__init__(speed, locate, direction, *args, **kwargs)
    

    如果您不确定星号的作用,this question 是一个很好的资源。

    【讨论】:

    • 另请注意,在您的具体情况下,您实际上并不需要 **kwargs,但最好将它们添加到类初始化中。
    【解决方案2】:

    这行得通。你打错了:def __int__( 应该是 def __init__(

    class X:
        def __init__(self, length, speed, locate, direction):
            self._len = length
            self._speed = speed
            self._locate = locate
            self._direction = direction
    
    
    class Y(X):
        def __init__(self, speed, locate, direction):
            super().__init__(3.0, speed, locate, direction)
    
    
    y = Y(10, 20, 30)
    
    print(y._len, y._speed, y._locate, y._direction)
    # prints 3.0 10 20 30
    

    【讨论】:

      【解决方案3】:

      我会建议下面的代码

      class Y(X):
              def __int__(self, speed, locate, direction):
                  X.__init__(3.0, speed, locate, direction)
      
      

      这里有几点需要注意

      • 我更喜欢使用父类名 (X),因为它在多重继承的情况下是明确的
      • 现在你的 y 类使用父类的 _len 成员
      • 我建议避免使用 *args, **kwargs,因为显式优于隐式,你不知道你想要在超类中添加新参数的行为,所以最好在这种情况下生成错误,这样你可以明确决定如何处理它们

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-18
        • 1970-01-01
        • 2022-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多