在childclasspython3中获取superclass输入参数

Get superclass input parameter in child class python3

我需要一些帮助来理解 python3.6 中的以下问题。 我有 2 classes:parent & child。 child 继承 parent。 我需要在 parent class.

中访问 child 中的变量 declared/passed

但是当我 运行 命令时:

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

观察:

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

注意:**kwargs 用于 child class 因为它需要在 运行 时接受变量输入,这有效。

TIA

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

class parent:

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

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

class child(parent):

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

def test_func(self):
    return self.fmt

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

Step1 -- 将变量'abc'传递给child

child(fmt='abc').test_func()

# this works, the variables goes into the child's __init__ function

Step2 -- child 应该交给 parent

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

Step3 -- parent 赋值

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

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

  • [最佳]删除child的__init__方法,现在变量将直接传递给parent的__init__方法,完全跳过Step2。
  • 通过转发任何提供的变量(因此 super().__init__(**kwargs))修复 child 的 __init__ 方法