仅当尝试在Python中访问时,才可以创建成员变量吗?

问题描述 投票:0回答:1

我创建了一个简单的类,其中包含一些成员变量和方法来解释我的问题。

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

此处创建了“ specificString”,并在实例化对象(因为它在对象构造器中)时创建了“ getSpecificString()”的返回值。

但是,有一种方法可以确保仅在程序尝试访问“ self.specificString”时才创建它”>

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

我可以轻松使用成员函数,(但是由于某些原因,在这种情况下,我宁愿不使用)

randomClass.getSpecificString()

...成员函数将检索字符串并设置成员变量的位置

换句话说,当我尝试访问变量“ specificString”时,我只想运行“ getSpecificString()”。

我创建了一个简单的类,其中包含一些成员变量和方法来解释我的问题。类cRandomClass:def __init __(self,book):self.largeTextString = book#...

python
1个回答
0
投票

您可以将specificString设为类方法,并在其上放置@property装饰器。像这样


0
投票

您可以将specificString设为类方法,并在其上放置@property装饰器。像这样

© www.soinside.com 2019 - 2024. All rights reserved.