对象继承和嵌套cmd [英] object inheritance and nested cmd

查看:138
本文介绍了对象继承和嵌套cmd的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个基本的OO问题:
我试图做一个嵌套的控制台菜单与cmd已经很好。
我还希望所有的子控制台都能访问相同的对象。这不太好。

This is probably a basic OO question: I'm trying to do a nested console menu with cmd which has gone well. I also want all my sub-consoles to have access to the same objects. This has not gone well.

我的简单示例:

import cmd
class MainConsole(cmd.Cmd):
    def __init__(self,obj1,obj2):
        cmd.Cmd.__init__(self)
        self.prompt = ">"
        self.obj1 = obj1 # The objects I want access to in all my consoles.
        self.obj2 = obj2
        self.menu1 = SubConsole1() # I could pass in the objects here as arguments
        self.menu2 = SubConsole2() # but there should be a better way.

    def do_menu1(self,args):
        self.menu1.cmdloop()
    def do_menu2(self,args):
        self.menu2.cmdloop()
    def do_info(self,args):
        self.menu1.do_info(args)
        self.menu2.do_info(args)
    def do_exit(self,args):
        return -1

class SubConsole1(cmd.Cmd,MainConsole):
    def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = "1>"
    def do_action(self,args):
        print self.obj1.someattr1 # Doesn't work

class SubConsole2(cmd.Cmd,MainConsole):
    def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = "2>"
    def do_action(self,args):
        print obj1.someattr2 # Doesn't work


class anobject(object):
    def __init__(self,init_value):
        self.someattr1 = init_value
        self.someattr2 = init_value * 2

object1 = anobject(1)
object2 = anobject(2)
c=MainConsole(object1,object2)
c.cmdloop()

运行这个我得到

>
>menu1
1>info
AttributeError: SubConsole1 instance has no attribute 'obj1'

请重试。

>
>menu2
2>info
NameError: global name 'obj1' is not defined

我不确定SubConsoles是否应该是 MainConsole 的子类。我还尝试在 MainConsole 里嵌套SubConsoles。

I'm not sure if the SubConsoles should be sub-classes of MainConsole. I also tried nesting the SubConsoles inside of MainConsole.

推荐答案

不需要多重继承,但是你需要给继承的对象赋予obj1和obj2,除非你给obj1和obj2一些默认值。

You don't need multiple inheritance, but you need to give obj1 and obj2 to the inherited objects, except if you give some default values to obj1 and obj2.

class SubConsole1(MainConsole):
    def __init__(self, obb1, obj2):
        MainConsole.__init__(self, obj1, obj2)
        self.prompt = "1>"
    def do_action(self,args):
        print self.obj1.someattr1 # Doesn't work

instanciated by:

instanciated by :

sub1 = SubConsole1(object1, object2)

这篇关于对象继承和嵌套cmd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆