0
class Range:
    GOOD=(1,100)
    BAD=(200, 300)

class Test:
    def test1(self):
        key = get_map_key()
        range = Range.key

What is the correct way to use constant defined in Range? The "key" is computed from a function. Possible value for "key" is GOOD, BAD.

susanna
  • 1,395
  • 3
  • 20
  • 32
  • You can refer to the constants as e.g. `Range.GOOD`. – Michael Butscher Jan 10 '20 at 03:49
  • 1
    Runtime lookups like this could be better done with a dictionary. With languages that don't have reflection (e.g. C++), that's certainly the way you would have to do it. – Mateen Ulhaq Jan 10 '20 at 03:50
  • 1
    But, otherwise, take a look `Range.__dict__`. It contains `GOOD` and `BAD` as keys. If you want to do a lookup, one way is `Range.__dict__["GOOD"]`, but more canonically, there's also `getattr(Range, "GOOD")`. – Mateen Ulhaq Jan 10 '20 at 03:51

1 Answers1

1

If you want get the attribute of an object using a string you need use getattr function. With this function you can access to an object attribute with the name of that attribute as str:

class Test:
    def test1(self):
        key = get_map_key()#assuming it return 'BAD'
        range = getattr(Range, key)

With this you have dynamic access to attributes. For this case it access to BAD property of Range class.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
juancarlos
  • 593
  • 3
  • 9