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

Python27:使用类型对类进行子类化,python,python-2.7,Python,Python 2.7,我有以下课程 class Sample(object): def __init__(self, argument, argument2, argument3): self.value = argument self.value2 = argument2 self.value3 = argument3 我想通过使用type创建这个类的一个子类,但是我不确定如何填充\uuu___方法的参数 我还有一个自定义的\uuuu_uu\uu方法,用于填

我有以下课程

class Sample(object):
    def __init__(self, argument, argument2, argument3):
        self.value = argument
        self.value2 = argument2
        self.value3 = argument3
我想通过使用type创建这个类的一个子类,但是我不确定如何填充\uuu___方法的参数

我还有一个自定义的\uuuu_uu\uu方法,用于填充对象:

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

myclass = type("TestSample", (Sample,), dict(__init__=setup))
myclass('some', 'argument', 'values')
但是,当我执行以下操作时:

myclass()
我得到:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: setup() takes exactly 4 arguments (1 given)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:setup()只接受4个参数(给定1个)

有没有一种方法可以在不必在对象安装时提供这些值的情况下预先填充这些值?

您的子类工作正常,但您为它提供了自己的
\uuuuu init\uuu
方法,该方法仍然需要四个位置参数。其中一个是
self
,但在创建对象时仍需要提供其他3个:

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

myclass = type("TestSample", (Sample,), dict(__init__=setup))
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')

您可能正在寻找默认参数,编写为
def(x=1,y=2,…)(…)
。但是请注意,这些是可变的,例如,如果您使用容器类型(list、dict、set等)作为默认参数并向其添加值,则在下一次调用时仍将具有该值。哦!所以,如果我提供默认参数,那么由于修改了init方法,它们不会生效吗?我会给那一个GO为什么如果我做一个部分的设置它不工作?i、 e.dict(uu init_uuu=partial(setup,argument=“good”,argument2=“day”,argument3=“sir”)),同时删除默认参数。这不等同于第一个和第二个安装示例吗?@Har:
functools.partial()
对象不实现描述符协议,因此不能用作方法。Python3.4添加了一个这样做的函数。哇,谢谢。我以前没见过描述符协议,我会研究一下it@Har当前位置在这个问题上有点争议。