2013-06-24 37 views
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()時,如何使Servers()類中包含的繼承函數display()接收選項tuple和sub_menu =「Server Menu」字符串?Python類繼承函數和從子項傳遞參數

+0

ncurses對這類事情有很多幫助,不是嗎? –

回答

4

可以在display功能使用self.optionsself.sub_menu,但是爲什麼你在BaseMenu類一無所知optionssub_menu引用它們呢?

第二個問題,您將"server"參數傳遞給__init__不帶任何參數的類,因此您需要添加該參數。

如果你打算永遠不會實例化一個BaseMenu對象,那麼它就是一個抽象基類(或ABC)。你可以把它定義爲這樣使用蟒蛇abc模塊以確保繼承類定義的屬性,你期待:

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 
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> 

難道合適?

+0

是的,這看起來像是我想要做的感謝。 – dman

+0

好的,這次更新和重新測試! –