z.ghane
z.ghane

Reputation: 301

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

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:

Upvotes: 4

Views: 12482

Answers (4)

rahi
rahi

Reputation: 34

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.

Upvotes: 1

nose_gnome
nose_gnome

Reputation: 131

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.

Upvotes: 0

mxp-xc
mxp-xc

Reputation: 504

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

Upvotes: 2

fırat dede
fırat dede

Reputation: 163

write it with self keyword like self.PAD_token.

Upvotes: 0

Related Questions