假设我有一个具有通用方法(add
)的类,并且我想创建一个新类RandomPair
,它将包含一对同一类的对象并将 add
分派(dispatch)到随机的一个。
例如,
class C1 (object):
def __init__ (self, title, plus = True):
self.title = title
self.plus = plus
self.acc = 0
def add (self, x):
if self.plus:
self.acc += x
else:
self.acc -= x
def __str__ (self):
return "C1(%s,%g)" % (self.title,self.acc)
class C2 (object):
def __init__ (self, title):
self.title = title
self.all = list()
def add (self, x, pos = None):
if pos:
self.all.insert(pos,x)
else:
self.all.append(x)
def __str__ (self):
return "C2(%s,%s)" % (self.title,self.all)
import random
class RandomPair (object):
def __init__ (self, klass, title, **kwargs):
self.objects = [klass(title + "#" + str(i), kwargs) for i in range(2)]
def add (self, *args, **kwargs):
self.objects[random.randint(0,1)].add(args,kwargs)
def __str__ (self):
return "\n".join([str(o) for o in self.objects])
现在,我希望能够做到
rp1 = RandomPair(C1,"test")
rp1.add(1)
rp1.add(2)
rp2 = RandomPair(C2,"test")
rp2.add(1)
rp2.add(2, pos=0)
但我明白了
TypeError: add() got multiple values for keyword argument 'self'
在self.objects[random.randint(0,1)].add(args,kwargs)
中。
最佳答案
您需要应用 args 和 kwargs,使用与定义参数时类似的符号。您需要在两个地方执行此操作;在 RandomPair.__init__()
和 RandomPair.add()
中:
self.objects = [klass(title + "#" + str(i), **kwargs) for i in range(2)]
和
self.objects[random.randint(0,1)].add(*args, **kwargs)
否则你只是传递两个参数,一个元组和一个字典。
你的下一个问题在C2.add()
中;您正在使用 pos
如果它为空;你想反转这个测试。更好的是,显式测试 None
:
def add(self, x, pos=None):
if pos is None:
self.all.append(x)
else:
self.all.insert(pos,x)
关于python - 创建一个分派(dispatch)到随机对象的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26552530/