为什么 First Class 函数符号在 class 方法中不起作用?

Why First Class Function Notation is not working in the class methods?

你好希望你们一切顺利。

我有一个 class,它有几个方法,我有一个运行器,它随机执行几个 class 方法中的一个函数。我曾尝试在 runner 函数中使用 First Class Function 方法,但 runner 无法识别函数名称。谁能告诉我为什么?

我的代码:

import random


class A:
    def delete_random_character(self, s):
        """Returns s with a random character deleted"""
        if s == "":
            return s

        pos = random.randint(0, len(s) - 1)
        # print("Deleting", repr(s[pos]), "at", pos)
        return s[:pos] + s[pos + 1:]


    def insert_random_character(self, s):
        """Returns s with a random character inserted"""
        pos = random.randint(0, len(s))
        random_character = chr(random.randrange(32, 127))
        # print("Inserting", repr(random_character), "at", pos)
        return s[:pos] + random_character + s[pos:]


    def flip_random_character(self, s):
        """Returns s with a random bit flipped in a random position"""
        if s == "":
            return s

        pos = random.randint(0, len(s) - 1)
        c = s[pos]
        bit = 1 << random.randint(0, 6)
        new_c = chr(ord(c) ^ bit)
        # print("Flipping", bit, "in", repr(c) + ", giving", repr(new_c))
        return s[:pos] + new_c + s[pos + 1:]


    def runner(self, s):
        """Return s with a random mutation applied"""
        mutators = [
            delete_random_character, ################ Cant recognizes the function why????
            insert_random_character, 
            flip_random_character
        ]
        mutator = random.choice(mutators)
        # print(mutator)
        return mutator(s)

您没有使用对 class 函数的引用来初始化 mutators;你应该

mutators=[
    self.delete_random_character,
    self.insert_random_character, 
    self.flip_random_character
]