【问题标题】:How do inherit list items in Python?如何在 Python 中继承列表项?
【发布时间】:2015-02-27 11:19:50
【问题描述】:

我正在学习 Python 中的面向对象编程并制作一个冒险游戏。

每个房间都是一个继承自 Scene 类的对象实例。在每个房间中,我都有一个可以在该房间中使用的命令列表。程序根据该列表检查用户输入,以查看命令是否匹配(然后继续执行适当的功能:去另一个房间,拿起钥匙,诸如此类)。

我希望 Scene 类包含任何房间的库存命令列表(帮助、库存等)。但是当引擎检查每个特定房间中的命令时,它会覆盖超类中的命令列表。如何更改此代码,以便 Castle(Scene) 类中的命令中的项目也包含 Scene(object) 类中的命令中的项目?

对不起,如果这对你们来说有点基本。这里有类似的问题,但我无法在我的代码中真正理解它们。我是 OOP 新手。

class Scene(object):
    commands = [
        'help',
        'inventory'
        ]

    def action(self, command):
        if command == 'inventory':
            print "You are carrying the following items:"
            # function to display items will go here


class Castle(Scene):
    def enter(self):
        print "You are in a castle"

    commands = [
        'get key',
        'east'
        ] 

    def action(self, command):
        if command == 'get key':
            print "You pick up the key"
            return 'castle'
        elif command == 'east':
            print "You go east"
            return 'village'
        else:
            pass
        return(0)

【问题讨论】:

  • 您必须在Castle 中扩展commands。请不要为commands 类赋值。只需扩展它并添加新值。`
  • 听起来commands 应该是将命令字符串映射到行为的映射。但是,这对于您需要的东西来说太复杂了。删除commands 并让action 做它需要做的事情。此外,您需要定义action 返回的内容,并让Castle.action 首先调用super().action(command) 并检查返回值。

标签: python oop inheritance


【解决方案1】:

你可以使用属性:

>>> class A(object):
...     @property
...     def x(self):
...         return [1]
...
>>>
>>> class B(A):
...     @property
...     def x(self):
...         return super(B, self).x + [2]
...
>>> b = B()
>>> b.x
[1, 2]
>>>

【讨论】:

  • 谢谢。这样可行。不过,它会引发一大堆其他问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 2021-07-20
  • 1970-01-01
  • 2014-04-10
  • 1970-01-01
相关资源
最近更新 更多