Home > Software engineering >  How to access class variable inside methods of that class in python?
How to access class variable inside methods of that class in python?

Time:12-20

  • Operating System: Windows, 64bit
  • Python Version: 3.7.11
  • IDE: Jupyter Notebook (with conda env)

I have below code:

class Vocabulary(object):
    
    PAD_token = 0
    
    def __init__(self):
        self.index2word = {PAD_token: "PAD"}

# create object
voc = Vocabulary()

I want to use PAD_token class variable inside __init__ method but I got below error:

NameError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_8472/897996601.py in <module>
----> 1 voc = Vocabulary()

~\AppData\Local\Temp/ipykernel_8472/3780152240.py in __init__(self)
      4 
      5     def __init__(self):
----> 6         self.index2word = {PAD_token: "PAD", SOS_token: "SOS", EOS_token: "EOS"}

NameError: name 'PAD_token' is not defined

Question:

  • How can I use PAD_token class variable inside __init__ or other methods of the class?

CodePudding user response:

There are two ways to access it

first: self.__class__.PAD_token

second: self.PAD_token

If you just need to access class variables, the first one is recommended

CodePudding user response:

To access any class variable from within the object, you need to put self. in front of the variable name.

This means that to call PAD_token you need to use self.PAD_TOKEN

Your code should look like this.

class Vocabulary(object):
    
    PAD_token = 0
    
    def __init__(self):
        self.index2word = {self.PAD_token: "PAD"}

# create object
voc = Vocabulary()

If you do not add the self it will think you are trying to access a local variable named PAD_token, and there isn't a local variable that has been defined within that method with that name, that is why it is throwing that not defined error.

CodePudding user response:

write it with self keyword like self.PAD_token.

CodePudding user response:

You are trying access variable that you assigned in your class. Here PAD_token can be called as class variable.

you can access it by class name Vocabulary.PAD_token or by self self.PAD_token.

In your case dictionary will place its value to the key i.e.

{0:"PAD"} #ignoring other keys

because you have assigned that to 0 in initialization.

  • Related