【问题标题】:Class Variable NameError not defined python类变量 NameError 未定义 python
【发布时间】:2018-06-20 14:26:00
【问题描述】:

在这个例子中,它正在工作 酒店作为类变量没有 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")

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

更新

对于第一个示例,没有调用显示错误 但是第二个例子的问题解决了感谢 Tom Dalton、scharette 和 James

【问题讨论】:

  • 当您调用for i in customers: customers 不在该功能范围内。
  • 试试for i in self.customers:
  • @TomDalton 谢谢它现在可以工作了,但是为什么在第一个例子中我没有使用 self.hotels 和它的工作原理?
  • 我不知道——你有没有在模块级别定义变量hotels
  • 它没有在其他任何地方定义,就像两个例子一样,它们是不同的文件。

标签: python class-variables


【解决方案1】:

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

我还想补充一点,你使用

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

但你也声明了

customers = []

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

基本上,

您希望在对象之间共享列表?

for i in Notifications.customers:

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

for i in self.customers:

【讨论】:

  • 你能解释一下为什么它在第一个例子中没有 Hotel.hotels 或 self.hotels 就可以工作
  • 我不希望将其添加到我的答案中,因为它应该不起作用。正如@James 所说,当您运行第一个示例时,您的全局(解释器)范围内有一个名为 hotels 的变量。 可能就是这种情况。
  • 实际上你解决了它,但我仍然对它在第一个示例中的工作方式有疑问,但这不会影响我的问题的主要要求。
  • 你能在你的解释器里试试吗?
  • @ahmedyounes,詹姆斯确实看过他的答案。
【解决方案2】:

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

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

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

这样您就可以使用 cls 变量访问类变量,而不必在函数中重复类名(这很好,就好像您更改了类名一样 - 您不必费力地寻找您的重复代码)。

【讨论】:

  • 感谢您的通知,但我正在尝试确认它会在不同的全局解释器范围内出错,但不会出错!!
  • 签入 locals() 也许?或者你可以在模块级别定义它吗?
  • 不,它没有在其他任何地方定义,就像我在问题中使用的示例一样,紧张起来真的很累:(
  • 你能在你的解释器里试试吗?
  • 我怎样才能删除或重置我的解释器,我重新启动了一切,仍然有这个问题我什至创建了一个新课程,对于酒店来说它没有给出错误!!!
猜你喜欢
  • 2022-01-10
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多