Python 全局变量和类功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16210314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:01:44  来源:igfitidea点击:

Python global variable and class functionality

pythonclass

提问by user2318861

Im creating a simple python program that gives basic functionality of an SMS_Inbox. I have created an SMS_Inbox method.

我创建了一个简单的 python 程序,它提供了 SMS_Inbox 的基本功能。我创建了一个 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. However for some reason it is not adding values to my global message_count variable.

我创建了一个全局变量存储,它是一个空列表,这在我使用 add_new_variable 对象时有效。但是由于某种原因,它没有向我的全局 message_count 变量添加值。

Please help

请帮忙

采纳答案by Eric

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

回答by Martijn Pieters

You are trying to assign to a global variable message_countwithout 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 classattribute:

尽量避免使用全局变量,或者至少将变量封装为属性:

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 instanceshave no state anymore, so there is no pointin 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 样式指南命名和字符串格式,将您的设置转换为实例保持状态的类:

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 oneinstance 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(...),但状态被封装在一个实例中。

回答by Sukrit Kalra

If the variable you are referring to is message_count, the error is because in Python, you have to specify a variable as globalbefore 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