【问题标题】:What's a better way of overriding nested class members in Python?在 Python 中覆盖嵌套类成员的更好方法是什么?
【发布时间】:2011-12-04 17:59:22
【问题描述】:

我需要“覆盖”一些基类的嵌套类成员,同时保持其余部分不变。
这就是我所做的:

class InternGenericForm(ModelForm):                
    class Meta:
        model = Intern
        exclude = ('last_achievement', 'program',)
        widgets = {
            'name': TextInput(attrs={'placeholder': 'Имя и фамилия' }),
        }

class InternApplicationForm(InternGenericForm):
    class Meta:
        # Boilerplate code that violates DRY
        model = InternGenericForm.Meta.model
        exclude = ('is_active',) + InternGenericForm.Meta.exclude
        widgets = InternGenericForm.Meta.widgets

事实上,我希望InternApplicationForm.MetaInternGenericForm.Meta 完全一样,只是它的exclude 元组应该包含一个以上的项目。

在 Python 中执行此操作的更漂亮的方法是什么?
我希望我不必编写像model = InternGenericForm.Meta.model 这样也容易出错的样板代码。

【问题讨论】:

    标签: python class inheritance syntax nested-class


    【解决方案1】:
    class InternGenericForm(ModelForm):                
        class Meta:
            model = Intern
            exclude = ('last_achievement', 'program',)
            widgets = {
                'name': TextInput(attrs={'placeholder': 'Имя и фамилия' }),
            }
    
    class InternApplicationForm(InternGenericForm):
        class Meta(InternGenericForm.Meta):
            exclude = ('is_active',) + InternGenericForm.Meta.exclude
    

    【讨论】:

      猜你喜欢
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-01
      • 2017-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多