user5423
user5423

Reputation: 145

Is there a way to create a member variable only when attempted to access in Python?

I have created a simple class that contains a few member variables and methods to explain my question.

class cRandomClass:
    def __init__(self, book):
        self.largeTextString = book

        ##self.getSpecificString() will search through the largeTextString variable to get the value 
        self.specificString = self.getSpecificString()


    def getSpecificString(self):
        ##Some code that searches for a string

Here "specificString" is created and the return value of "getSpecificString()" is stored, when the object is instantiated since it's in the object constructer.

However, is there a way where I can make sure "self.specificString" is created only when the program attempts to access it

randomClass = cRandomClass(book)
##I want to create the member variable when calling it, to trigger a function to return a value
randomClass.specificString

I could easily use a member function, (but for certain reasons and in this scenario I would rather not)

randomClass.getSpecificString()

...where the member function would retrieve the string and set the member variable

In other words, I want to only run "getSpecificString()" when I attempt to access the variable "specificString".

Upvotes: 0

Views: 137

Answers (1)

CumminUp07
CumminUp07

Reputation: 1978

You can make the specificString a class method and put the @property decorator on it. Like this

class cRandomClass:
    def __init__(self, book):
        self.largeTextString = book

        ##self.getSpecificString() will search through the largeTextString variable to get the value 


    def getSpecificString(self):
        ##Some code that searches for a string
        return 'string'

    @property   
    def specificString(self):
        return self.getSpecificString()

So when you 'access' cRandomClass.specificString it will just call getSpecificString()

Upvotes: 2

Related Questions