Why can't I access this member of a class in python?

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 the default value for a variable. However, this results in the following error:

NameError: name 'Transcription' is not defined

Why this is not possible and what is the correct (pythonic) way to do something like this.

+3
source share
3 answers

You cannot access it because it is Transcriptionnot defined at the time the statement is executed def.

 def align_transcription(self,model,target=PHONE):
        pass

will do the trick. The name is PHONEavailable in the namespace, which will become a class Transcriptionafter completion class.

, class - , . Python , , class, . , , type. , . , def.

class Foo(object):
    a = 1
    def foo(self):
        print self.a

ns = {'a': 1, 'foo': foo},

Foo = type('Foo', (object,), ns)

def foo(self):
    print self.a

Foo = type('Foo', (object,), {'a': 1, 'foo': foo})

, Foo Foo, Foo.a .

+11

.

( , Pythonic):

class Transcription(object):
    WORD = 1   # zero won't work below... need to change the value
    PHONE = 2
    STATE = 3

    def align_transcription(self, model, target=None):
        target = target or Transcription.PHONE
        # or
        if target is None: target = Transcription.PHONE

PHONE WORD . if , or PHONE.

align_transcription :

class Transcription(object):
    WORD = 0
    PHONE = 1
    STATE = 2

def _unbound_align_transcription(self, model, target=Transcription.PHONE):
    pass

Transcription.align_transcription = _unbound_align_transcription
+2

The transaction class does not yet exist when you define the align_transcription method, but the PHONE is available in the scope. So you can do this:

class Transcription(object):
    WORD = 0
    PHONE = 1
    STATE = 2

def __init__(self):
    self.transcriptions = []

def align_transcription(self,model,target=PHONE):
    pass

or with target = None by default if you plan to override PHONE in subclasses or instances:

def align_transcription(self,model,target=None):
    if target is None:
        target = self.PHONE
+1
source

Source: https://habr.com/ru/post/1784677/


All Articles