English 中文(简体)
避免在子类中指定所有参数
原标题:Avoid specifying all arguments in a subclass

我有一堂课。

class A(object):
    def __init__(self,a,b,c,d,e,f,g,...........,x,y,z)
        #do some init stuff

我有一个子类需要一个额外的参数(最后一个W)。

class B(A):
    def __init__(self.a,b,c,d,e,f,g,...........,x,y,z,W)
        A.__init__(self,a,b,c,d,e,f,g,...........,x,y,z)
        self.__W=W

似乎写所有这些样板代码很愚蠢, 比如将B的Ctor中的所有参数传递到内部调用A的Ctor中, 因为对A 的Ctor做出的每个更改都必须应用于B中的另外两个位置。

我猜Python有一些处理这种情况的习语,但我不知道。你能指导我吗?

我的最佳猜测是为A创建一种类似于复制构造函数的东西,然后将B的代码更改为...

class B(A):
     def __init__(self,instanceOfA,W):
         A.__copy_ctor__(self,instanceOfA)
         self.__W=W

这适合我的需求,因为当给出父类的实例时,我总是创建子类,虽然我不确定这是否可能...

最佳回答

考虑到参数可以通过名称或位置进行传递,我会编写代码:

class B(A):
    def __init__(self, *a, **k):
      if  W  in k:
        w = k.pop( W )
      else:
        w = a.pop()
      A.__init__(self, *a, **k)
      self._W = w
问题回答

编辑:根据马特的建议,并解决gnibbler对于位置参数方法的关注,您可以检查以确保指定了额外的子类特定参数-类似于Alex的答案。

class B(A):
  def __init__(self, *args, **kwargs):
    try:
      self._w = kwargs.pop( w )
    except KeyError:
      pass
    super(B,self).__init__(*args, **kwargs)

>>> b = B(1,2,w=3)
>>> b.a
1
>>> b.b
2
>>> b._w
3

Original answer:
Same idea as Matt s answer, using super() instead.

使用super()调用超类s的__init__()方法,然后继续初始化子类:

class A(object):
  def __init__(self, a, b):
    self.a = a
    self.b = b

class B(A):
  def __init__(self, w, *args):
    super(B,self).__init__(*args)
    self.w = w

在一些或全部传递给__init__的参数具有默认值的情况下,避免在子类中重复__init__方法签名可能是有用的。

在这些情况下,__init__可以将任何额外的参数传递给另一个方法,这些子类可以进行覆盖:

class A(object):
    def __init__(self, a=1, b=2, c=3, d=4, *args, **kwargs):
        self.a = a
        self.b = b
        # …
        self._init_extra(*args, **kwargs)

    def _init_extra(self):
        """
        Subclasses can override this method to support extra
        __init__ arguments.
        """

        pass


class B(A):
    def _init_extra(self, w):
        self.w = w

你想要这样的东西吗?

class A(object):
    def __init__(self, a, b, c, d, e, f, g):
        # do stuff
        print a, d, g

class B(A):
    def __init__(self, *args):
        args = list(args)
        self.__W = args.pop()
        A.__init__(self, *args)




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签