鱼C论坛

 找回密码
 立即注册
查看: 3407|回复: 4

[已解决]lesson 39 (为什么是:NameError: name 'list1' is not defined)

[复制链接]
发表于 2017-7-12 22:32:35 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
以下为程序执行结果:

>>> stack = Stack(5)
>>> stack.push()
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    stack.push()
  File "J:/python/python exercise/39 lesson/stack class.py", line 7, in push
    list1.append(self.x)
NameError: name 'list1' is not defined
>>>

以下为源程序:
class Stack:
    list1 = []
    def __init__(self, x):
        self.x = x
        
    def push(self):
        list1.append(self.x)

    def isEmpty(self):
        if Stack.list1:
            return True
        else:
            return False

    def pop(self):
        list1.pop(self.x)

    def top(self):
        return list1[-1]

    def bottom(self):
        return list1[0]
最佳答案
2017-7-13 07:08:29
  1. class Stack:
  2.     list1 = []
  3.     def __init__(self, x):
  4.         self.x = x
  5.         
  6.     def push(self):
  7.         self.list1.append(self.x)

  8.     def isEmpty(self):
  9.         if Stack.list1:
  10.             return True
  11.         else:
  12.             return False

  13.     def pop(self):
  14.         list1.pop(self.x)

  15.     def top(self):
  16.         return list1[-1]

  17.     def bottom(self):
  18.         return list1[0]
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-7-12 22:51:13 | 显示全部楼层
没问题呀。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-7-13 07:08:29 | 显示全部楼层    本楼为最佳答案   
  1. class Stack:
  2.     list1 = []
  3.     def __init__(self, x):
  4.         self.x = x
  5.         
  6.     def push(self):
  7.         self.list1.append(self.x)

  8.     def isEmpty(self):
  9.         if Stack.list1:
  10.             return True
  11.         else:
  12.             return False

  13.     def pop(self):
  14.         list1.pop(self.x)

  15.     def top(self):
  16.         return list1[-1]

  17.     def bottom(self):
  18.         return list1[0]
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-7-13 07:08:54 | 显示全部楼层
list那改成self.list
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-6-16 15:21:11 | 显示全部楼层

为什么 self.list1.append(self.x)这里将,liset1 改为了self.list1。
而list1.pop(self.x)这里可以不改?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-5 02:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表