gpt4 book ai didi

python - 类变量名称错误未定义python

转载 作者:行者123 更新时间:2023-12-01 01:48:44 25 4
gpt4 key购买 nike

在这个例子中,它正在工作酒店作为类变量没有 NameError

class Hotel():
"""""""""
this is hotel class file
"""
hotels = []
def __init__(self,number,hotel_name,city,total_number,empty_rooms):
self.number = number
self.hotel_name = hotel_name
self.city = city
self.total_number = total_number
self.empty_rooms = empty_rooms

Hotel.hotels.append([number,hotel_name,city,total_number,empty_rooms])

def list_hotels_in_city(self,city):
for i in hotels:
if city in i:
print "In ",city,": ",i[1],"hotel, available rooms :",i[4]

在下面的示例中它不起作用

from twilio.rest import Client


class Notifications():
customers = []

def __init__(self,customer_name,number,message):
self.customer_name = customer_name
self.number = number
self.message = message
Notifications.customers.append([customer_name,number,message])

def send_text_message(self,customer_name):
for i in customers:
print "triggeredb"

inst = Notifications("ahmed","+00000000000","messagesample")
print "instance : ",inst.customers
inst.send_text_message("ahmed")

名称错误:未定义全局名称“客户”

更新

对于第一个示例,没有调用任何内容来显示错误但第二个示例的问题已解决,感谢 Tom Dalton、scharette 和 James

最佳答案

正如我在评论中所说,当您在顾客中调用 for i: 时,customers 不在该函数的范围内。

我只是想补充一点,你使用

 Notifications.customers.append([customer_name,number,message])

但你也声明

customers = []

请注意,前者是一个变量,并将在Notifications实例之间共享该变量。后者代表一个实例变量。如果您的目标是为每个特定对象提供一个客户列表,则应使用self.customers

所以基本上,

您想要在对象之间共享列表吗?

for i in Notifications.customers:

您想要每个对象的特定列表吗?

for i in self.customers:

关于python - 类变量名称错误未定义python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50950574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com