Python - 函数数组类

时间:2013-09-09 14:28:17

标签: python-3.x

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

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

3 个答案:

答案 0 :(得分: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()

答案 1 :(得分: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方法返回{{1 }}

答案 2 :(得分: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()