Python27:使用类型对类进行子类化

时间:2015-05-19 09:49:09

标签: python python-2.7

我有以下课程

class Sample(object):
    def __init__(self, argument, argument2, argument3):
        self.value = argument
        self.value2 = argument2
        self.value3 = argument3

我希望使用 type 创建一个子类,但是我不确定如何填充 __ init __ 方法的参数。

我也有这个自定义 __ init __ 方法来填充对象:

def setup(self, arg, arg2, arg3):
    self.value = "good"
    self.value2 = "day"
    self.value3 = "sir"

myclass = type("TestSample", (Sample,), dict(__init__=setup))

然而,当我表演时:

myclass()

我明白了:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: setup() takes exactly 4 arguments (1 given)

有没有办法预先填充这些值,而无需在对象实例中提供它们?

1 个答案:

答案 0 :(得分:2)

你的子类工作正常,但你给它自己的__init__方法仍然需要四个位置参数。其中一个是self,但在创建对象时仍需要提供其他3个:

myclass('some', 'argument', 'values')

你的函数忽略那些参数,所以也许你不打算将它们包含在函数签名中?你不必在这里匹配父类:

def setup(self):
    self.value = "good"
    self.value2 = "day"
    self.value3 = "sir"

myclass = type("TestSample", (Sample,), dict(__init__=setup))

不是直接设置属性,而是可以将其委托给父类:

def setup(self):
    Sample.__init__(self, 'good', 'day', 'sir')

myclass = type("TestSample", (Sample,), dict(__init__=setup))

如果您希望这些默认可以覆盖,请使用关键字参数:

def setup(self, argument='good', argument2='day', argument3='sir'):
    Sample.__init__(self, argument, argument2, argument3)

myclass = type("TestSample", (Sample,), dict(__init__=setup))

现在您可以省略参数,或为它们提供不同的值:

c1 = myclass()
c2 = myclass(argument2='weekend')