繁体   English   中英

Python NameError:名称“...”未在类中定义

[英]Python NameError: name '...' is not defined in a class

我正在尝试制作一个很酷的回合制格斗游戏,但我的代码的一部分不喜欢我。 我有一个无法确定一些事情的菜单系统。 (请记住,我最近才开始上课。)

制作一个类实体(对于玩家和敌人)。

class Entity:
  def __init__(self):
    self.name = ''
    self.health = 0
    self.moveset = []

制作一个带有菜单的播放器类(以便我可以添加更多角色)。

 class Player(Entity):
      options = [menu(),attack(),items(),stats(),flee()]
      def menu(self):
        menuchoice = input('Menu\n1. Attack\n2. Items\n3. Stats\n4. Flee\n')
        if menuchoice not in ['1','2','3','4']:
          clear()
          options[0]
        options[int(menuchoice)]
        options[0]
      def attack(self):
        print('attack')
      def items(self):
        print('items')
      def stats(self):
        print('stats')
      def flee(self):
        print('flee')

试图运行菜单

player = Player()
player.menu()

错误

Traceback (most recent call last):
  File "main.py", line 16, in <module>
    class Player(Entity):
  File "main.py", line 17, in Player
    options = [menu(),attack(),items(),stats(),flee()]
NameError: name 'menu' is not defined

有人能告诉我如何在这段代码中定义菜单吗? 我正在使用 Python 3.6.1。

编辑:谢谢! 它现在有效。 我必须添加()并将options = [...]移到最后!

变量options可能旨在维护对可用选项的引用。 它正在做的是在定义方法之前调用方法本身:

这是一个演示问题的最小版本(它在 python 解释器本身上:

>>> class Player:
...     options = [menu()]
...     def menu(self):
...         print('menu')
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in Player
NameError: name 'menu' is not defined
>>>

这是另一个版本,没有实际调用方法,只是添加了引用。 它会遇到同样的错误:

>>> class Player:
...     options = [menu]
...     def menu(self):
...         print('menu')
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in Player
NameError: name 'menu' is not defined
>>>

这可能是你想要的:

>>> class Player:
...     options = ['menu']
...     def menu(self):
...         print('in menu')
...
>>> player = Player()
>>> player
<__main__.Player instance at 0x10a2f6ab8>
>>> player.options
['menu']
>>> player.options[0]
'menu'
>>> type(player.options[0])
<type 'str'>
>>> func = getattr(player, player.options[0])
>>> type(func)
<type 'instancemethod'>
>>> func
<bound method Player.menu of <__main__.Player instance at 0x10a2f6ab8>>
>>> func()
in menu
>>>

这是在定义后使用它的证明,它不会出错 - 但这不是标准/典型用法:

>>> class Player:
...     def menu(self):
...         print('in menu')
...     options = [menu]
...
>>> player = Player()
>>> player.options
[<function menu at 0x10a2f16e0>]
>>> player.options[0]
<function menu at 0x10a2f16e0>
>>> player.options[0]()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: menu() takes exactly 1 argument (0 given)
>>> player.options[0](player)
in menu
>>> Player.options[0](player)
in menu
>>> Player.options[0](player)   # calling with class reference
in menu
>>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM