Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access class variable inside methods of that class in python?

  • 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading