0

我应该如何实现以下课程?我想创建在调用时以随机顺序执行方法的类,并且在所有方法都被调用一次重置数组和重新洗牌之后?

import random

class RandomFunctions(object):

    def f1():
        print("1")
    def f2():
        print("2")
    def f3():
        print("3")

    f = [f1, f2, f3]

    def __init__(self):
        super(RandomFunctions, self).__init__()
        random.shuffle(self.f)

    def execute(self):
        func = self.f.pop()
        if not self.f:
            reset f
        return func

def main():
    f = RandomFunctions()
    for i in range(6):
        f.execute()()

main()

这是我提出的两个想法,但我仍然想知道实现这种类的最聪明的方法是什么?

discard = []
n = 0

    def execute(self):
        func = self.f[self.n]
        self.n += 1
        if self.n == len(self.f):
            self.n = 0
            random.shuffle(self.f)
        return func

    def execute_with_discard(self):
        func = self.f.pop(0)
        discard.append(func)
        if not self.f:
            f = discard[:]
            discard = []
            random.shuffle(self.f)
        return func
4

3 回答 3

2
import random

class RandomFunctions(object):

    def f1(self):
        print("1")

    def f2(self):
        print("2")

    def f3(self):
        print("3")

    def execute(self):
        if not getattr(self, 'functions', None):
            self.functions = [self.f1, self.f2, self.f3]
            random.shuffle(self.functions)
        return self.functions.pop()


def main():
    f = RandomFunctions()
    for i in range(6):
        f.execute()()


main()
于 2013-09-09T14:43:10.880 回答
1
import random

class RandomFunctions(object):

    def f1():
        print("1")
    def f2():
        print("2")
    def f3():
        print("3")

    f = [f1, f2, f3]

    def __init__(self):
        self.reset()

    def execute(self):
        func = self.f.pop()
        if not self.f:
            self.reset()
        return func()   # execute the function, return the result (if any)

    def reset(self):
        self.f = self.__class__.f[:]    # make copy of class f
        random.shuffle(self.f)

def main():
    f = RandomFunctions()
    for i in range(6):
        f.execute()     # now we only need one pair of parenthesis

main()
于 2013-09-09T15:37:19.570 回答
1

它必须是这样的类吗?您可以使用生成器功能:

def get_random_functions(*functions):
    while True:
        shuffled = list(functions)
        random.shuffle(shuffled)
        while shuffled:
            yield shuffled.pop()

for f in get_random_functions(f1, f2, f3):
    f()

当然,如果你喜欢你的类结构,你可以通过在你的__init__方法(self.gen = get_random_functions(*f))中创建生成器来使用它,然后让你的execute方法返回next(self.gen)

于 2013-09-09T14:44:28.893 回答