Zoltan
Zoltan

Reputation: 513

Using a variable as an attribute of a class

This works:

if event.key == pygame.K_LEFT:
    print('LEFT key pressed')

Now I try to set the LEFT key for the game with a string variable (by user input).

left_key = 'K_LEFT'

How can I use this variable as an attribute of pygame? Something like this:

if event.key == pygame.left_key:
    print('LEFT key pressed')

Thanks for the help.

Upvotes: 2

Views: 37

Answers (2)

skrx
skrx

Reputation: 20438

You can use the getattr function:

if event.key == getattr(pygame, left_key):

Upvotes: 1

Reblochon Masque
Reblochon Masque

Reputation: 36662

You could assign K_LEFT to left_key:

left_key = K_LEFT

instead of left_key = 'K_LEFT'

Upvotes: 1

Related Questions