-1

In the following code, I defined self.dir in the match case

class Enemies(pygame.sprite.Sprite):
    def __init__(self):

        self.image = pygame.image.load("picture.png").convert_alpha()
        self.seat = random.choices(
            (range(1, 13)), weights=(1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3))

        match self.seat:
            case 1:
                self.dir = 315
                self.rect = self.image.get_rect(bottomright=(0, 0))
                # there are many more cases but they are similar

        print(self.dir)

When I run the code, in the print(self.dir) part, it returned an AttributeError. But I defined self.dir in the match case. Do you think it is match case's problem or am I missing something?

Edit: it's not the match case's problem. random.choices() returns a list and in the match case, it needs an int.

  • When you printed something *within* each `case` statement what happened? – wwii May 17 '22 at 13:43
  • [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). [How to step through Python code to help debug issues?](https://stackoverflow.com/questions/4929251/how-to-step-through-python-code-to-help-debug-issues). [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). – wwii May 17 '22 at 13:45
  • 1
    [random.choices](https://docs.python.org/3/library/random.html#functions-for-sequences) returns a list, not an integer. Maybe use `random.choice` instead. – wwii May 17 '22 at 13:57
  • @wwii I tried random.choices(usual thing)[0] and it worked. If I want to use random.choice, I cannot have weighted results tho. should I just stick with random.choices()[0] ? – Justin Case May 17 '22 at 14:27
  • .. stay with `random.choices()[0]` if you need them to be weighted. Or try `self.seat,*_ = random.choices(...`. Or `[self.seat] = random.choices(...`. – wwii May 17 '22 at 16:20

1 Answers1

0

self.dir will only exist if the random is equal to 1. set this variable out of scope so that it always exists.

self.dir = None

match self.seat:
    case 1:
        self.dir = 315
        self.rect = self.image.get_rect(bottomright=(0, 0))
        # there are many more cases but they are similar

print(self.dir)
  • While this will alleviate the `AttributeError` problem, it is not the *answer* - the match/case statements still won't work. – wwii May 17 '22 at 14:00
  • This is the answer to the issue title 'match case can't access attribute'. But thanks for the feedback. The variable type in match case can be solved in several ways. – Gustavo Marquezinho May 17 '22 at 14:04
  • Thank you for your reply. I did some testing after the post and there's nothing wrong with the match case. wwii pointed out that random.choices() returns a list and that is the problem. – Justin Case May 17 '22 at 14:30