0

I have this class Knop (meaning 'button') with the following constructor:

def __init__(self, rechthoek, kleur = BUTTONCOLOR, actie = printtest, tekst = "", tekstkleur = BUTTONTEXTCOLOR, actie_args = {}, score = -1 ):

    self.rechthoek = rechthoek # pygame.Rect object
    self.kleur = kleur # button color: (r,g,b) tuple
    self.actie = actie # the function to call when pressing the button
    self.actie_args = actie_args # the arguments to the function actie
    self.tekst = tekst # the text in the button
    self.tekstkleur = tekstkleur # the color of the text
    self.score = score

The idea is that the function actie is called with the arguments actie_args (which is a dict) as follows: return_val = self.actie(**self.actie_args).

Now, somewhere else, I make a list knoppen (meaning 'buttons') by creating new instances:

knoppen = []
for i, emotie in enumerate(emoties):
    ypos = y[4] + FONTSIZE*i*2 - FONTSIZE/4
    r = pygame.Rect(xpos, ypos, buttonwidth, buttonheight)
    eknop = Knop(r, emo_kleur[i], tekst = emoties[i])
    eknop.actie = set_emotie
    eknop.tekstkleur = BLACK
    knoppen.append(eknop)

And a little later on in the program:

cnt_rect = pygame.Rect(x[1], y[8], x[3], y[1])
bknop = Knop(cnt_rect, BUTTONCOLOR, tekst = TXT_CONFIRM)
bknop.actie = bevestig
bknop.actie_args["annfile"] = appvars["saved_utterances"]
bknop.actie_args["utt_i_file"] = appvars["gebleven_bij_utterance"]
knoppen.append(bknop)

Now, when these latter block is executed, a problem arises. The actie_args argument of bknop seems to be 'copied' to the actie_args of all the other buttons created before. I tested this by making a __str__ function within the Knop class and printing an eknop before and after creating the bknop.

What is this caused by and how can I solve this?

Lewistrick
  • 2,649
  • 6
  • 31
  • 42
  • Thanks for the reference to the duplicate @jonrsharpe, but I find it hard to apply that to my situation. Is there anything I can do to make it work as I want to? – Lewistrick Feb 25 '15 at 11:16
  • 1
    See e.g. http://stackoverflow.com/q/28677657/3001761 – jonrsharpe Feb 25 '15 at 11:17

0 Answers0