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



我尝试创建实例变量,但它似乎不起作用。我希望我的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

在类的顶部添加:

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

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

...
if self.data_list:
do_something()

最新更新