1

Basically, why do these work:

class MyClass:
    Dict={['A','B','C'][i]:{['a','b','c'][j]:[1,2,3][j] for j in range(3)} for i in range(3)}

and

class MyClass:
    Table = ['A','B','C']
    Dict={Table[0]:'a',Table[1]:'b',Table[2]:'c'}

but not this one?

class MyClass:
    Table = ['A','B','C']
    Dict={Table[i]:['a','b','c'][i] for i in range(3)}

I'm trying to consolidate a bunch of arrays, interpolation functions, and solvers by putting them all in classes. Each array contains a number of different properties so I figured the best way to sort this data was through nested dictionaries (Many of the tables aren't complete so I can't use numpy arrays or even lists very effectively because the indices change depending on the line of the data). I've worked out all the other kinks, but for some reason moving it into a class gives me an error:

NameError: name 'Table' is not defined

I'm an engineering student and basically only learned how to use scipy solvers and integrators; everything else is self taught. Don't be afraid to tell me I'm doing everything wrong :)

martineau
  • 119,623
  • 25
  • 170
  • 301
Ryan Chou
  • 23
  • 4
  • 2
    Does this answer your question? [Accessing class variables from a list comprehension in the class definition](https://stackoverflow.com/questions/13905741/accessing-class-variables-from-a-list-comprehension-in-the-class-definition) ecatmur@ on the first answer also has a fun workaround using a lambda to force the binding. – Erich Jan 26 '21 at 21:56
  • @martineau Sorry, those were two _different_ examples of things that worked. – Ryan Chou Jan 27 '21 at 17:03

2 Answers2

0

I think you are trying to do a Dictionary Comprehension, but weird enough, this message error you receive does not make much sense to me.

Anyway, with this implementation it worked just fine for me:

class MyClass:
    Table = ['A','B','C']
    Dict= {i:j for i,j in zip(Table, ['a','b', 'c'])}
    
0

This is a class variable + comprehension scope issue. Table is not defined inside your dictionary comprehension, and in the other definition which uses Table you are not doing a comprehension.

You may want to use __init__ here.

Erich
  • 1,902
  • 1
  • 17
  • 23