首页 > 解决方案 > 为什么我在代码中定义的全局变量中出现 NameError?

问题描述

我试图在 Person1 类下的另一个方法中使用变量“action”,但它不断给出 NameError。

import random

message_box= []
shared_files_box= []

class Chat():
    def __init__(self):
        x= ['Online', 'Offline']
        self.availability=random.choice(x)


class Message():

    def __init__(self,):
        # 0 means Sent, 1 means Not Sent, 2 means delivered, 3 means read
        self.y=[0,1,2,3]
        self.message_status=random.choice(self.y)



class Person1(Chat,Message):

    def __init__(self):
        Chat.__init__(self)
        Message.__init__(self)
        self.name = input(" Enter Username: ").upper()
        self.phone_num = "08023416789"
        prefix = ['A', 'B', 'C', 'D','E','F','J','Z']
        suffix = random.randint(1111, 9999)
        self.user_ID = []
        my_choice= random.choice(prefix)
        for j in my_choice:
            x= j + str(suffix)
            self.user_ID.append(x)
        



    def __str__(self):

        return "Username: {}, Phone Number: {}, User ID: {}, Availability: {}".format(self.name,self.phone_num,self.user_ID,self.availability)


    def message_to_send(self):
        global action
        print("Press 1 to send text message\nPress 2 to share file")
        action=int(input("Please what do you want to do ? "))
        return action

    def file_types(self):
        file_type = ['Audio', 'Video', 'Voice Notes', 'text message' 'other files']
        share_files = random.choice(file_type)
        return share_files

    def sendMessageFormats(self):


        if self.availability== 'Online':

            if action == 1:
                self.text_message_entry = input("Insert text message: ")
                if self.message_status== 0:
                    print(self.text_message_entry, "sent successfully !!!!!!!!")
                else: print(" Message not sent. Try again !!!!")

            elif action == 2: # You are ready to share files

                if self.message_status== 0:
                    print(self.file_types(), "sent successfully !!!!!!!!")
                else: print(" Message not sent. Try again !!!!")


            else: print("Choose between options 1 OR 2 : ")
        else: print(self.name,"You are Offline, On your data please and try again") # Data is not yet on so user is offline

    def receiveMessageFormats(self):
        if self.availability == 'Online' :
            if action ==1:
                message_box.append(self.message_to_send())
                print(message_box)

            elif action ==2:
                shared_files_box.append(self.file_types())
                print(shared_files_box, "received")

            print("Message received and Read: {}".format(self.sendMessageFormats()))


        elif self.availability == 'Online' and  self.message_status==2 :
            return "Message Delivered but not Read: {}".format(self.sendMessageFormats())

        else:
            return "Message not Read: {}".format(self.sendMessageFormats())


p=Person1()
p.receiveMessageFormats()

我的 IDE 给我的输出如下所示:

NameError: name 'action' is not defined

标签: python-3.x

解决方案


sendMessageFormats并且receiveMessageFormats您在定义变量之前引用该action变量(python假定本地范围,因此您必须global在这些函数中使用关键字让语言知道您想要全局变量而不是您忘记定义的某些局部变量)。

请参阅https://www.programiz.com/python-programming/global-local-nonlocal-variables#:~:text=In%20Python%2C%20a%20variable%20declared,variable%20is%20created%20in%20Python。以获得更大的解释。

此外,全局变量是 99/100,这不是正确的模式。如果您能找到一种在给定场景中不使用全局变量的好方法,通常最好不要使用它们,除非有令人信服的理由。


推荐阅读