创建一个调度到随机对象的类

时间:2014-10-24 16:47:10

标签: python random

假设我有一个具有公共方法(add)的类,并且我想创建一个新类RandomPair,它将包含同一类的一对对象并调度{{1}一个随机的。

,例如,

add

现在,我希望能够做到

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' 中的

1 个答案:

答案 0 :(得分:2)

您需要应用 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)
相关问题