python-3.x - 为什么我在代码中定义的全局变量中出现 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
解决方案
在sendMessageFormats
并且receiveMessageFormats
您在定义变量之前引用该action
变量(python假定本地范围,因此您必须global
在这些函数中使用关键字让语言知道您想要全局变量而不是您忘记定义的某些局部变量)。
此外,全局变量是 99/100,这不是正确的模式。如果您能找到一种在给定场景中不使用全局变量的好方法,通常最好不要使用它们,除非有令人信服的理由。
推荐阅读
- javascript - 在 React 上构建帖子点赞功能
- windows - 用于自动化 curl POST 身份验证的 Bash 函数未按预期执行
- android - RatingBar 触摸位置不准确
- c++ - 带有 Rcpp 头文件的 c++ 文件的编译步骤
- javascript - 控制台不会从 ATOM 中的 js 文件运行我的代码?**初学者
- ruby-on-rails - 在 Ruby on Rails 中检查 has_many 关系中的记录
- r - 预测丢弃 svm 观察
- ios - 更新了所有设备的启动映像命名约定
- php - 通过 ajax 将输入文件类型传递给 php 不起作用
- xml - Sorting and deleting XML document elements using PowerShell