避免在子类中指定所有参数 [英] Avoid specifying all arguments in a subclass

查看:24
本文介绍了避免在子类中指定所有参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课:

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

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

And I have a subclass which needs one extra arg (the last 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 构造函数的每一次更改都必须应用到 B 代码中的另外两个地方.

It seems dumb to write all this boiler-plate code, e.g passing all the args from B's Ctor to the inside call to A's ctor, since then every change to A's ctor must be applied to two other places in B's code.

我猜 python 有一些习惯用法来处理我不知道的这种情况.你能指出我正确的方向吗?

I am guessing python has some idiom to handle such cases which I am unaware of. Can you point me in the right direction?

我最好的预感是对 A 使用一种 Copy-Ctor,然后将 B 的代码更改为

My best hunch, is to have a sort of Copy-Ctor for A and then change B's code into

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

这将满足我的需求,因为我总是在给定父类的实例时创建子类,尽管我不确定这是否可能...

This would suit my needs since I always create the subclass when given an instance of the father class, Though I am not sure whether it's possible...

推荐答案

考虑到参数可以通过名称或位置传递,我的代码是:

Considering that arguments could be passed either by name or by position, I'd code:

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

这篇关于避免在子类中指定所有参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆