【问题标题】:Get superclass input parameter in child class python3在子类python3中获取超类输入参数
【发布时间】:2021-05-07 19:41:57
【问题描述】:

我需要一些帮助来理解 python3.6 中的以下问题。 我有2个班级:父母和孩子。子继承父。 我需要访问在父类中声明/传递的变量。

但是当我运行命令时:

命令:child(fmt='abc').test_func()

观察:

  1. 这会返回默认值'X',但我期待的是'abc' 被退回。 -- 所以传递的值不起作用。
  2. 如果我在 test_func 中返回变量 self.mode, 它返回我正确的值。 -- 所以声明的值是有效的。

注意:**kwargs 用于子类,因为它需要在运行时接受变量输入,这是可行的。

TIA

================================================ ==========================

类父级:

def __init__(self, fmt = 'X'):
    self.fmt = fmt
    self.mode = 'abc'

================================================ ==========================

类子(父):

def __init__(self, **kwargs):
    super().__init__()   

def test_func(self):
    return self.fmt

================================================ ==========================

【问题讨论】:

    标签: python-3.x inheritance parent-child super


    【解决方案1】:

    Step1 -- 将变量'abc'交给孩子

    child(fmt='abc').test_func()
    
    # this works, the variables goes into the child's __init__ function
    

    第二步——孩子应该把它交给父母

    def __init__(self, **kwargs):
        # the variable is here
        super().__init__()  
        # but never gets passed or assigned anywhere
    

    Step3 -- 父级分配它

    def __init__(self, fmt = 'X'):
        # your input of 'abc' never reaches here
        self.fmt = fmt
    

    两种可能的解决方案。要么

    • [BEST] 删除子级的__init__ 方法,现在变量将直接传递给父级的__init__ 方法,完全跳过Step2。
    • 通过转发任何提供的变量来修复孩子的__init__ 方法(所以super().__init__(**kwargs)

    【讨论】:

      猜你喜欢
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多