Is there any way to reference an Enum inside itself in Python?

Asked

Viewed 76 times

0

I would like to use a constant I created in an Enum as an attribute of another, for example:

from enum import Enum


class Jokenpo(Enum):
    PEDRA = ('Rock', [Jokenpo.PAPEL], [Jokenpo.TESOURA])
    PAPEL = ('Paper', [Jokenpo.TESOURA], [Jokenpo.PEDRA])
    TESOURA = ('Scissors', [Jokenpo.PEDRA], [Jokenpo.PAPEL])


    def __init__(self, nome, fraco, forte):
        self.nome = nome
        self.fraco = fraco
        self.forte = forte

In a game of stone-paper-scissors, to specify which stone loses to paper but wins scissors I can do something similar to that. Probably mine In one has some errors, I’m beginner, but it has how to use a constant within another?

  • Sounds like the problem XY. I analyze that you want to implement the logic of the game instead of actually having this doubt about enums.

1 answer

0


There is, but not the way you’re doing it, although it’s not really a problem to create a enumerable from tuples, but the logic itself has gotten pretty strange.

Bearing in mind that each value of the Enum will be an instance of the Enum, you can define a property that returns the weakness and strength of each item. For example:

from enum import Enum

class Jokenpo(Enum):
    PEDRA = 1
    PAPEL = 2
    TESOURA = 3

    @property
    def weakness(self):
        if self == self.PEDRA:
            return self.PAPEL
        elif self == self.PAPEL:
            return self.TESOURA
        else:
            return self.PEDRA

print(Jokenpo.PEDRA.weakness)  # Jokenpo.PAPEL
print(Jokenpo.PAPEL.weakness)  # Jokenpo.TESOURA
print(Jokenpo.TESOURA.weakness)  # Jokenpo.PEDRA

See working on Repl.it | Ideone | Github GIST

Browser other questions tagged

You are not signed in. Login or sign up in order to post.