简体   繁体   English

Python全局变量和类功能

[英]Python global variable and class functionality

Im creating a simple python program that gives basic functionality of an SMS_Inbox. 我创建了一个简单的python程序,它提供了SMS_Inbox的基本功能。 I have created an SMS_Inbox method. 我创建了一个SMS_Inbox方法。

store = []
message_count = 0
class sms_store:
    def add_new_arrival(self,number,time,text):
        store.append(("From: "+number, "Recieved: "+time,"Msg: "+text))
        **message_count += 1**
    def delete(self,i):
        if i > len(store-1):
            print("Index does not exist")
        else:
            del store[i]
            message_count -= 1

In the bolded bit I am getting an error: 在粗体位我得到一个错误:

UnboundLocalError: local variable 'message_count' referenced before assignment.

I created a global variable store which is an empty list and this works when I use the add_new_variable object. 我创建了一个全局变量存储,它是一个空列表,这在我使用add_new_variable对象时有效。 However for some reason it is not adding values to my global message_count variable. 但是由于某种原因,它没有向我的全局message_count变量添加值。

Please help 请帮忙

That's not how classes work. 这不是班级的工作方式。 Data should be stored within the class instance, not globally. 数据应存储在类实例中,而不是全局存储。

class SMSStore(object):
    def __init__(self):
        self.store = []
        self.message_count = 0

    def add_new_arrival(self,number,time,text):
        self.store.append(("From: "+number, "Recieved: "+time,"Msg: "+text))
        self.message_count += 1

    def delete(self, i):
        if i >= len(store):
            raise IndexError
        else:
            del self.store[i]
            self.message_count -= 1

sms_store = SMSStore()
sms_store.add_new_arrival("1234", "now", "lorem ipsum")
try:
    sms_store.delete(20)
except IndexError:
    print("Index does not exist")

print sms_store.store

# multiple separate stores
sms_store2 = SMSStore()
sms_store2.add_new_arrival("4321", "then", "lorem ipsum")
print sms_store2.store

If the variable you are referring to is message_count , the error is because in Python, you have to specify a variable as global before you can make edits with it. 如果您引用的变量是message_count ,则错误是因为在Python中,您必须先将变量指定为global变量,然后才能对其进行编辑。

This should work. 这应该工作。

store = []
message_count = 0
class sms_store:
    def add_new_arrival(self,number,time,text):
        global message_count
        store.append(("From: "+number, "Recieved: "+time,"Msg: "+text))
        message_count += 1
    def delete(self,i):
        if i > len(store-1):
            print("Index does not exist")
        else:
            global message_count
            del store[i]
            message_count -= 1

As written above, you'd be better off encapsulating it in the __init__ function instead of declaring it global . 如上所述,最好将其封装在__init__函数中,而不是将其声明为global函数。

You are trying to assign to a global variable message_count without declaring it as such: 您正在尝试分配给全局变量message_count而不声明它:

message_count = 0

class sms_store:
    def add_new_arrival(self,number,time,text):
        store.append(("From: "+number, "Recieved: "+time,"Msg: "+text))
        global message_count
        message_count += 1

Try to avoid using globals, or at least encapsulate the variable as a class attribute: 尽量避免使用全局变量,或者至少将变量封装为属性:

class sms_store:
    message_count = 0
    store = []

    def add_new_arrival(self,number,time,text):
        sms_store.append(("From: "+number, "Recieved: "+time,"Msg: "+text))
        sms_store.message_count += 1

However, your class instances have no state anymore, so there is no point in creating a class here. 但是,您的类实例不再具有状态,因此在此处创建类没有意义 It only serves to confuse your purpose. 它只会混淆你的目的。

Either store state in instances, or use global functions (so don't use a class at all); 要么在实例中存储状态,要么使用全局函数(所以根本不要使用类); the former is preferable to the latter. 前者优于后者。

Transforming your setup to a class whose instances hold state, using proper PEP-8 styleguide naming and string formatting: 使用正确的PEP-8 styleguide命名和字符串格式将您的设置转换为实例保持状态的类:

class SMSStore(object):
    def __init__(self):
        self.store = []
        self.message_count = 0

    def add_new_arrival(self, number, time, text):
        self.store.append('From: {}, Received: {}, Msg: {}'.format(number, time, text))
        self.message_count += 1

You are then free to create one instance and use that as a global if needs be: 然后,您可以自由创建一个实例,并在需要时将其用作全局实例:

sms_store = SMSStore()

Other code just uses sms_store.add_new_arrival(...) , but the state is encapsulated in one instance. 其他代码只使用sms_store.add_new_arrival(...) ,但状态封装在一个实例中。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM