使用其他类的默认初始化值

use*_*583 5 python python-3.x

我有两个具有一些功能的类:

class A:
   def __init__(self, one=1, two=2):
      self.one = one
      self.two = two

   def do_smt(self):
      ...

class B:
   def __init__(self, value="test"):
      self.value = value

   def do_smt(self):
      ...
Run Code Online (Sandbox Code Playgroud)

我有一个必须使用这两个类的第三个类正在这样做。

class C:
   def __init__(self, one=1, two=2, value="test"):
      self.A = A(one, two)
      self.B = B(value)

   def do_smt(self):
      ...
Run Code Online (Sandbox Code Playgroud)

现在我这样做:new_class = C()

但是如果默认值发生class A or B变化怎么办,那么我还需要在class C. 有没有一种方法class C可以知道哪些参数是默认参数?它不需要处理任何参数,但也需要处理其他类期望的参数。

sch*_*ggl 0

您可以使用一些哨兵值(此处None)并仅在参数作为有意义的内容提供时才传递参数:

class C:
   def __init__(self, one=None, two=None, value=None):
      if one is two is None:
          self.A = A()
      else:
          self.A = A(one, two)
      if value is None:
          self.B = B()
      else:
          self.B = B(value)
Run Code Online (Sandbox Code Playgroud)

这样,AandB的默认值就会自行处理。