Home > Mobile >  How to call my own method from a list in Python3?
How to call my own method from a list in Python3?

Time:11-02

I am trying to make a machine code interpreter, in which, for the sake of effectiveness, I would like to use a direct relation between the code and the function that emulates its function. As I imagined, I would put emulating functions into an indexed list, and will call the appropriate function indexing the list by the machine code byte. My problem is that I do not know, how to wording the list members for internal methods of my class (it would not work neither with "self." nor with "myclass." prefix, too). Sample code below shows my problem: in functions[] list I would list that methods, what I want to connect with the indexes of the list. Please suggest me, what would the best (and hopefully the fastest executing) solution in Python 3.

class myclass:

    values = [101, 102, 103, 104,105, 106, 107, 108]
    functions = [getval, getnextval, getprevval]

    def __init__(self):
        pass

    def getval(self, index):
        return self.values[index]

    def getnextval(self, index):
        return self.values[index   1]

    def getprevval(self, index):
        return self.values[index - 1]

    def getfuncval(self, func, index):
        return(self.functions[func](index))


myobj = myclass()
print(myobj.getval(0))          # -> 101
print(myobj.getnextval(1))      # -> 103
print(myobj.getfuncval(2, 3))   # would need to get result from getprevval(3) -> 103

CodePudding user response:

You can move the definition of functions into __init__.

def __init__(self):
    self.functions = [self.getval, self.getnextval, self.getprevval]

There are a couple of other options, such as using classmethods. (Since your methods don't seem to rely on any internal state of a particular myclass instance.)

CodePudding user response:

You are not assigning any value to values and functions variables into the self object, maybe this code is the solution:

class myclass:    
    def __init__(self):
        self.values = [101, 102, 103, 104,105, 106, 107, 108]
        self.functions = [self.getval, self.getnextval, self.getprevval]

    def getval(self, index):
        return self.values[index]

    def getnextval(self, index):
        return self.values[index   1]

    def getprevval(self, index):
        return self.values[index - 1]

    def getfuncval(self, func, index):
        return(self.functions[func](index))


myobj = myclass()
print(myobj.getval(0))          # -> 101
print(myobj.getnextval(1))      # -> 103
print(myobj.getfuncval(2, 3))
  • Related