gpt4 book ai didi

Python27 : Subclassing a class by using type

转载 作者:行者123 更新时间:2023-12-01 04:42:17 25 4
gpt4 key购买 nike

我有以下类(class)

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)

有没有办法预先填充这些值,而不必在对象实例化时提供它们?

最佳答案

您的子类工作正常,但您给了它自己的 __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))

您仍然可以将其委托(delegate)给父类,而不是直接设置属性:

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')

关于Python27 : Subclassing a class by using type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30322161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com