为继承类设置常量参数的最佳实践

时间:2017-06-30 16:02:29

标签: python inheritance

我的课程it "#active_consent_run" do consent_run = create(:consent_run, :in_progress) consent_question = create(:consent_run_question, consent_run: consent_run) # I guess it’s an active record ⇓ for illegal status consent_run.update_column :status, 4 expect(consent_question.valid?).to eq false expect(consent_question.errors[:consent_run_id]).to \ eq(['needs to be in progress']) end 定义如下:

GUI

我想基于GUI定义子类table_color = "red" class GUI: def __init__(self): self.draw_table() def draw_table(self): print "table color: ", table_color

GUI_child

但是上述table_color = "blue" class GUI_child(GUI): def __init__(self): GUI.__init__(self) 不起作用并打印“红色”。我有一堆像GUI_child这样的变量只在初始化时使用过一次。我知道我可以将table_color定义为类变量,或者在table_color中再次定义draw_table(),但感觉这些可能不是最佳选择。

(编辑:由于这些变量只使用一次,我不打算更改或访问它们,将它们设置为类变量似乎是多余的。如果我重新定义GUI_child它只是复制粘贴,在我看来,这也不是一个好习惯。)

这种用法的最佳做法是什么?

1 个答案:

答案 0 :(得分:1)

将定义table_color = "red"移到class GUI定义的最开头,并在类的方法中使用self.table_color引用它。将它移动到类中使它成为一个类属性,将由派生类继承。

但是,您可以通过在子类定义中重新定义它(以相同的方式)来覆盖子类中的值,以覆盖父类中原本将被继承的那个。

这就是我的意思:

class GUI:
    table_color = "red"

    def __init__(self):
        self.draw_table()

    def draw_table(self):
        print("table color: {}".format(self.table_color))

class GUI_child(GUI):
    table_color = "blue"

    def __init__(self):
        super(GUI_child, self).__init__()

gui = GUI()              # -> table color:  red
gui_child = GUI_child()  # -> table color:  blue

注意根据PEP 8 - Style Guide for Python Code,常量应全部为大写。这意味着table_color应更改为TABLE_COLOR

相关问题