Search code examples
pythonfirst-class-functions

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


Hello Hope you guys are doing well.

I have a class which has several methods and I have a runner which randomly executes a function out of the several class methods. I have tried using First Class Function methodology in runner function but runner does not recognizes the function names. Can anybody tell my why?

My code:

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)

Solution

  • You are not using references to your class functions initializing mutators; you should

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