2
class BaseMenu(object):
    def display(self):
        header = "FooBar YO"
        term = getTerminalSize()
        #sys.stdout.write("\x1b[2J\x1b[H")
        print header.center(term, '*')
        #print sub_menu.center(term, '+')
        print "Please choose which option:"
        for i in options:
            print(
                str(options.index(i)+1) + ") "
            )

class Servers(BaseMenu):
    def __init__(self):
        #super(Servers, self).__init__("server")
        pass

    def list_foo(self):
        pass
    def list_bar(self):
        pass
    options = (
        list_foo,
        list_bar
        )

尝试从 Main Menu -> Servers 子菜单开始制作一系列文本菜单。当 Servers() 从 BaseClass 继承 display() 时,如何使继承的函数 display() 接收 Servers() 类中包含的选项 tuple 和 sub_menu = "Server Menu" 字符串?

4

2 回答 2

4

您可以在函数中使用self.optionsand ,但为什么在对or一无所知的类中引用它们?self.sub_menudisplayBaseMenuoptionssub_menu

第二个问题,您将"server"参数传递给一个不带参数的类,__init__因此您需要添加它。

如果您打算从不实例化一个BaseMenu对象,那么它是一个抽象基类(或ABC)。您可以使用 pythonsabc模块来定义它,以确保继承类定义您期望的属性:

import abc

class BaseMenu(object):
    __metaclass__ = abc.ABCMeta  #indicate that this is an ABC

    @abc.abstractproperty  # prevent derived classes that don't have options
    def options(self):
        pass

    @abc.abstractproperty
    def sub_menu(self):
        pass

    def __init__(self, menu_name): # takes the menu name as an argument ("server")
        self.menu_name = menu_name

    def display(self):
        header = "FooBar YO"
        term = getTerminalSize()
        print header.center(term, '*')
        print self.sub_menu.center(term, '+') # NOTE self.sub_menu
        print "Please choose which option:"
        for i in self.options: # NOTE self.options
            print(self.options.index(i)+1 + ") ")

如果任何类尝试从 BaseMenu 继承而不定义optionssub_menu它会在实例化时导致TypeError类似以下内容:

TypeError: Can't instantiate abstract class Servers with abstract methods options
于 2013-06-25T00:06:57.790 回答
2

我不确定我是否完全理解您在这里的要求,所以请告诉我,这个怎么样?

class BaseMenu(object):

    # Added some attributes here:
    menuName = ""
    options = ()

    def __init__(self, menu_name, opt):
        self.menuName = menu_name  # = "Servers Menu" when instantiated as Server
        self.options = opt         # the passed when instantiated as Server

    def display(self):

        # Use self.menuName and self.options here

        #...
        for i in self.options:
            print(
                str(self.options.index(i)+1) + ") " + str(i)
            )

class Servers(BaseMenu):

    def list_foo(self):
        pass
    def list_bar(self):
        pass

    options = (
        list_foo,
        list_bar
        )

    def __init__(self, menu_name):
        super(Servers, self).__init__(menu_name, self.options) 

像这样实例化 Servers类:

servers = Servers("Servers Menu")
servers.display()

输出:

1) <function list_foo at 0x29e06e0>
2) <function list_bar at 0x29e0758>

它适合吗?

于 2013-06-25T00:19:08.530 回答