简体   繁体   English

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

[英]how to access my variable from one method to another in same class?

I tried creating instance variable but it doesn't seem to be working. 我尝试创建实例变量,但似乎无法正常工作。 I want my data_list value in some other script with providing any argument. 我想要我的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

Add at the top of your class: 在课程顶部添加:

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

Then further down check whether it has been assigned before using it: 然后在使用前进一步检查是否已分配:

...
if self.data_list:
    do_something()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在基于django类的视图中从同一个类中的另一个方法访问一个方法的变量 - how to access variable of one method from another method within the same class in django class based views 如何从同一个类中的另一个方法访问一个类中的方法中的变量 - How to access a variable in a method in a class from another method in the same class 如何从同一类中的另一个方法访问方法变量(Tkinter)? - How to access a method variable (Tkinter) from another method in same class? 如何在同一个类中从一种方法访问列表到另一种方法 - How to access the list from one method to another in the same class 如何在Python中从一个类访问类方法和类变量到另一个类的实例方法? - How to access class method and class variable from a class to another class's instance method in Python? 从同一类中的另一个方法调用变量 - Calling a variable from another method in the same class 如何在同一个 class 内的另一种方法中以一种方法调用变量? - How do I call the variable in one method in another method inside the same class? 如何在同一类的另一个方法中调用方法的变量 - How to call a variable of a method in another method of the same class 如何从另一个模块的类访问变量 - How to access a variable from a class of another module 如何从另一个函数访问变量 - How to access a variable from one function in another
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM