I have the following code
class Transcription(object):
WORD = 0
PHONE = 1
STATE = 2
def __init__(self):
self.transcriptions = []
def align_transcription(self,model,target=Transcription.PHONE):
pass
The important part here is that I would like to have a class member as default value for a variable. This however gives the following error:
NameError: name 'Transcription' is not defined
Why is this not possible and what is the right (pythonic) way to do something like this.
You can’t access it because
Transcriptionisn’t defined at the time that thedefstatement is running.will do the trick. The
PHONEname is available in the namespace which will become theTranscriptionclass after theclassstatement finishes executing.The way this works is that
classis a statement that actually gets run. When Python encounters a class statement, it enters a new local scope and executes everything that’s indented under theclassstatement as if it were a function. It then passes the resulting namespace, the name of the class and a tuple of the baseclasses to the metaclass which istypeby default. The metaclass returns an instance of itself which is the actual class. None of this has occurred when thedefstatement executes.The statement
creates a namespace
ns = {'a': 1, 'foo': foo}and then executesThis is equivalent to
You can clearly see that
Foois not defined at the time thatfoois being defined soFoo.amakes no sense.