OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Python failed to initialize a 2d array as class attributes

  • Thread starter Thread starter Hongdan Wang
  • Start date Start date
H

Hongdan Wang

Guest
I am implementing a transition tables as a class attribute with,

Code:
class Phase:
    num_states = 15
    transition_table = [[False for _ in range(num_states)] for _ in range(num_states)]

but it failed with NameError: name 'num_states' is not defined. However, 1d array works as expected,

Code:
class Phase:
    num_states = 15
    transition_table = [False for _ in range(num_states)] # this works

I was wondering why this is the case, as num_states is defined before transition_table and it should have access to the previous one?
<p>I am implementing a transition tables as a class attribute with,</p>
<pre><code>class Phase:
num_states = 15
transition_table = [[False for _ in range(num_states)] for _ in range(num_states)]
</code></pre>
<p>but it failed with <code>NameError: name 'num_states' is not defined</code>.
However, 1d array works as expected,</p>
<pre><code>class Phase:
num_states = 15
transition_table = [False for _ in range(num_states)] # this works
</code></pre>
<p>I was wondering why this is the case, as num_states is defined before transition_table and it should have access to the previous one?</p>
 

Latest posts

S
Replies
0
Views
1
Sergey Bakaev Rettley
S
Top