Python类继承函数和从子传递参数

时间:2013-06-24 23:51:45

标签: python class inheritance

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
        )

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

2 个答案:

答案 0 :(得分:4)

您可以在self.options函数中使用self.sub_menudisplay,但为什么要在BaseMenu类中引用它们,options类对sub_menu一无所知}或"server"

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

如果您打算永远不会实例化abc对象,那么它是抽象基类(或 ABC )。您可以使用pythons 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 + ") ") 模块来定义它,以确保继承类定义您期望的属性:

options

如果任何类在没有定义sub_menuTypeError的情况下尝试从BaseMenu继承,则会在实例化时产生类似以下内容的TypeError: Can't instantiate abstract class Servers with abstract methods options

{{1}}

答案 1 :(得分: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>

适合吗?