Python父类检查要在类函数中使用的子类中的属性

时间:2013-06-29 21:19:55

标签: python class object inheritance

我正在编写这个Python(2.7)脚本,它是一系列菜单。对于每个子菜单,都有一个继承BaseMenu的子类。有一个名为SubMenu的子类,我想在子菜单名称的标题下打印server_name。在BaseMenu()中,我尝试使用if语句来检查属性是否存在,如果是,则打印它:

def display(self):
        header = "FooBar YO"
        term = getTerminalSize()
        #sys.stdout.write("\x1b[2J\x1b[H")
        print header.center(term, '*')
        print self.menu_name.center(term, '+')
    ###Below is the check
    if self.modify_server_class:
            print self.modify_server_class.center(term, '+')

当我尝试运行其他没有该属性的类时,它无效并抱怨AttributeError: 'Servers' object has no attribute 'modify_server_class'

如何让BaseClass检查此属性并将其打印(如果存在)?我不想将属性放在每个类中并将其设置为false。似乎可能有一种更清洁的方式。

class BaseMenu(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractproperty
    def options(self):
        pass

    @abc.abstractproperty
    def menu_name(self):
        pass

    def display(self):
        header = "FooBar YO"
        term = getTerminalSize()
        #sys.stdout.write("\x1b[2J\x1b[H")
        print header.center(term, '*')
        print self.menu_name.center(term, '+')
    if self.modify_server_class:
            print self.modify_server_class.center(term, '+')
        print "Please choose which option:"
        for i in self.options:
            print(
                str(self.options.index(i)+1) + ") "
                + i.__name__
            )
        while True:
        value = int(raw_input("Please Choose[ENTER to exit]: ")) - 1

        try:
        if value == "":
            break
        else:
            #with Redirect(self.file_object):
            self.options[value](self)
            self.display()
        except IndexError:
        print "Out of range!"


class ModifyServer(BaseMenu):
    def __init__(self, a):
    self.servers_object = a

    menu_name = "Modify Server"
    server_chosen = "None"
    modify_server_class = "hi"

    def choose_server(self):
    if not self.servers_object.servers:
        cs = pyrax.cloudservers
        self.servers_object.servers = cs.servers.list()
    temp = self.servers_object.servers
    for index, item in enumerate(temp):
        print (
        "%s) %s" % (index+1, item.name)
        )

    def jj(self):
    pass

    options = (
        choose_server,
    jj
    )

1 个答案:

答案 0 :(得分:2)

您可以为BaseMenu创建一个构造函数,用于设置此属性或使用hasattr()