Calling another class function in a loop in current class

Viewed 811

I have 2 class Emoji and EmojiRun. I want to call Emoji class function through EmojiRun, using a infinite loop

class Emoji:
    def __init__(self):
        self.green = (0, 255, 0)
        self.yellow = (255, 255, 0)
        self.blue = (0, 0, 255)
        self.red = (255, 0, 0)
        self.white = (255, 255, 255)
        self.nothing = (0, 0, 0)
        self.brown = (165, 42, 42)

    def face(self):
        return face

    def smile(self):
        return smile

    def sad(self):
        return sad

In my EmojiRun class, I need to call function face, smile, sad. I can call it individually, but I want to know if there is an way of iterate through Class Emoji's function, like the example below, I know its wrong

#Main class to run Emoji
from animatedEmoji import Emoji
from sense_hat import SenseHat
from time import sleep

#Class instance emoji
emoji = Emoji()
sense = SenseHat()

while True:
  #Forloop to call emoji functions 1 by 1
  for x in Emoji:
     sense.set_pixels(emoji.function[x])
     sleep(3)
2 Answers

You can add a function that gives you all the expressions that an Emoji supports:

class Emoji:
    ... // same code as before
    def expressions(self):
        yield self.face
        yield self.smile
        yield self.sad

You could then call it with:

e = Emoji()
for exp in e.expressions():
    sense.set_pixels(exp())
    sleep(3)

Instead of providing bound memberfunctions, you could probably just as well invoke them and yield their results.

This approach works as long as there are just a handful of expressions. Once you have many of them, maintaining the expressions() function becomes cumbersome. Even more so when you have derived classes. In that case, I'd suggest you research two alternative approaches:

  • Introspection. Basically, it means that you scan an object for methods that e.g. take no parameters (other than self) and return an expression. That probably requires return type annotations on the functions.
  • Registering expressions. Read the documentation for decorators, which allow you to write one that maintains a list of expression functions for each type. All you have to do is to prefix the function declaration with a @expression_function then.

you can try and see if the following works

>>> for k,v in Emoji.__dict__.items():
...   if "function" in str(v):
...     print(k)
... 
sad
smile
face
__init__
Related