0

How can a Python class constant be initialized once, and shared across instances? This is the line of thinking:

class X():
    # initialize a constant that will be used by all instances
    with open("list_of_valid_words.txt", "r") as f:
        VALID_WORDS = [ a.strip() for a in f.readlines() ]

    def __init__(self, var):
        self.var = var
    def valid_object(self):
        if self.var in VALID_WORDS: return True
        else: return False

a = X("this")
a.valid_object()
NameError: name 'VALID_WORDS' is not defined
CarlosE
  • 858
  • 2
  • 11
  • 22

1 Answers1

0

Use a class method to initialize the shared variable:

class X():
    @classmethod
    def class_init(cls):
        with open("list_of_valid_words.txt", "r") as f:
            cls.VALID_WORDS = [ a.strip() for a in f.readlines() ]

    def __init__(self, var):
        self.var = var
        
    def valid_object(self):
        if self.var in self.VALID_WORDS: return True
        else: return False

X.class_init()

Now we can instantiate objects and test them:

a = X("word")
a.valid_object()
True
CarlosE
  • 858
  • 2
  • 11
  • 22
  • Try `self.VALID_WORDS` directly - you don't have to use that `class_init`. – iBug Feb 21 '21 at 12:17
  • Thank you @iBug. Some people recommend pulling the class object via cls=self.__class__ do you have a view on this? Is it purely stylistic? – CarlosE Feb 22 '21 at 05:01