代码之家  ›  专栏  ›  技术社区  ›  Ahmed Younes

类变量名称错误未定义python

  •  1
  • Ahmed Younes  · 技术社区  · 6 年前

    在这个例子中,它是有效的 酒店作为类变量无名称错误

    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")
    

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

    更新

    例如,没有调用任何内容来显示错误 但第二个例子解决了这个问题,谢谢汤姆·道尔顿、沙雷特和詹姆斯。

    2 回复  |  直到 6 年前
        1
  •  1
  •   scharette    6 年前

    正如我在评论中所说, 当你打电话的时候 for i in customers: ,请 customers 不在该函数的范围内。

    我只是想补充一下,你用

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

    但是你也声明

    customers = []
    

    注意前者是 变量,并将在 Notifications 实例。后者代表 实例变量 .如果你的目标是 客户 列出每个特定对象,您应该使用 self.customers .

    所以基本上,

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

    for i in Notifications.customers:
    

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

    for i in self.customers:
    
        2
  •  1
  •   James    6 年前

    我认为当您运行第一个示例时,很可能在全局(解释器)范围内有一个名为hotels的变量。这就是它起作用的原因。如果我复制粘贴您的示例到我的解释器中,它将失败,错误消息与您的第二个代码示例相同。

    如果您的send_text_message函数只访问类变量(没有实例变量),我建议将其设置为如下类方法:

    @classmethod
    def send_text_message(cls, customer_name):
        for i in cls.customers:
            print "triggeredb"
    

    这样,您就可以使用cls变量访问类变量,并且不必在函数中重复类名(这很好,就像您更改类名一样,您不必搜索代码进行重复)。