0

I'm new to classes in python and am looking for someone to explain why I'm running into this issue.

I have this class:

class TrackingMeasure:
    Touches = 'Possessions'
    DefensiveImpact = 'Defense'

When I attempt to run this loop:

tracking_refs = ['Touches','DefensiveImpact']
for x in tracking_refs:
    print(TrackingMeasure.x)

I get this error:

AttributeError: type object 'TrackingMeasure' has no attribute 'x'

I'm sure this will be very easy for someone to explain so any help would be greatly appreciated.

Nick
  • 367
  • 4
  • 16
  • Why do you need to do this? It would likely be much better to have an internal dictionary, and just do a lookup of the dictionary. – Carcigenicate Mar 03 '19 at 23:30

3 Answers3

1

You would need to use the internal dict of the class to do that:

print(TrackingMeasure.__dict__[x])
Alain T.
  • 40,517
  • 4
  • 31
  • 51
1

You can use getattr:

tracking_refs = ['Touches','DefensiveImpact']
for x in tracking_refs:
    print(getattr(TrackingMeasure, x))
iz_
  • 15,923
  • 3
  • 25
  • 40
1

getattr(object,string)

this_tm = TrackingMeasure
for x in tracking_refs:
    print(getattr(this_tm,x))