0

In an effort to clean up a stretch of code I attempted something like this:

class ClassDirection():
    def __init__(self):
        pass

    def downward(self, x):
        print (x)

    def upward(self, x):
        print (X +1)

    def sideways(self, x):
        print (x // 2)

directions = []
mustard = ClassDirection()
dicty = {downward:5, upward:7, sideways:9}
for a,b in dicty.items():
    direction = mustard.a(b)
    directions.append(direction)

Seeing as the word "downward" is understood by python as a name that is undefined, it of course doesn't run giving me the error:

NameError: name 'downward' is not defined

I have 2 questions about this. A) Is there a way to store an undefined "name" in a dictionary without storing it as a string and then reformatting with some kind of crazy hack? B) Is it even possible to "inject" a part of a namespace like this?

chmedly
  • 391
  • 1
  • 6
  • 16
  • Sure, just store strings and use `getattr()`. Or store the bound methods; `mustard.downwards` is an object you can put in a dictionary, then later call. – Martijn Pieters Jul 12 '17 at 15:17
  • Thank you! getattr is the kind of thing I was looking for and I've learned a lot by looking at it's examples. btw, I recognize that the underlying mechanism in my question may be a duplicate but the path to finding it might not be. In fact, I spent quite a bit of time searching here and the google in general about this before asking my question. The issue was "how do I describe what I'm looking for". 'How to dynamically access class properties in Python?' is not at all how I was looking at the question. – chmedly Jul 14 '17 at 22:20

1 Answers1

0
dicty = {mustard.downward: 5, mustard.upward: 7, mustard.sideways: 9}
for a, b in dicty.items():
    direction = a(b)

Or:

dicty = {'downward': 5, 'upward': 7, 'sideways': 9}
for a, b in dicty.items():
    direction = getattr(mustard, a)(b)

Also, a dict isn't really helpful here and means you have no control over order. Rather:

dicty = [('downward', 5), ('upward', 7), ('sideways', 9)]
for a, b in dicty:  # no .items()
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
  • Thank you! getattr is the kind of thing I was looking for and I've learned a lot by looking at it's examples. As far as the dictionary goes: for some reason I felt that it was a more straightforward way to access the values at the time since I did NOT need to keep track of the order. But on further thought a straightforward list is probably better. – chmedly Jul 14 '17 at 22:25