Using an Enum as a flag in a class, Python -


i use enum represent internal state of class:

#!/usr/bin/python3 enum import enum   class testclass:     class color(enum):         red = 1         blue = 2         green = 3      def __init__(self):         self.value = 0      def setvalue(self, color):         self.value = color 

this thought possible implementation. 2 annoying things see are:

  1. to set value have :

    q = testclass()

    q.setvalue(q.color.red)

    and find q.color.red someway umpleasant, i'd rather have like:color.red or red. maybe way have use string comparison, trying avoid using enum.

  2. i method q.color.mro seems internal method of enum class. for?

alternative #1: can have enum class string lookup you:

    def setvalue(self, color):         self.value = self.color[color] 

usage:

q = testclass() q.setvalue('red') 

reference:


alternative #2: if there no conflicts, can promote enum's members parent class:

class testclass:     class color(enum):         red = 1         blue = 2         green = 3     red = color.red     blue = color.blue     green = color.green      def setvalue(self, color):         self.value = color 

usage:

q = testclass() q.setvalue(q.red) 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -