如何在同一个类中从一个方法访问我的变量?

时间:2018-05-16 10:59:48

标签: python python-3.x

我尝试创建实例变量,但它似乎没有工作。我希望我的data_list值在其他脚本中提供任何参数。

class MqttData:
    def on_connect(self,client, userdata, flags, rc):
        print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
        client.subscribe(TOPIC)

# The callback for when a PUBLISH message is received from the server.
    def on_message(self,client, userdata, msg):
        global count 


        data=msg.payload.decode('ascii')
        self.data_list=data.split('\n')
        print(self.data_list)
    #updatesheet.update_spreadsheet(data_list)

    def justafunction(self):
        return self.data_list

1 个答案:

答案 0 :(得分:0)

在课程顶部添加:

def __init__(self):
    self.data_list = None   # initialises to None at class instantiation

然后在使用之前进一步检查是否已分配:

...
if self.data_list:
    do_something()