2011-10-10 36 views
6

Tôi cần phải "ghi đè" một số thành viên lớp lồng nhau của lớp cơ sở, trong khi vẫn giữ nguyên phần còn lại.
Đây là những gì tôi làm:Cách tốt hơn để ghi đè thành viên lớp lồng nhau bằng Python là gì?

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 

Trong thực tế, tôi muốn InternApplicationForm.Metachính xác như InternGenericForm.Meta, ngoại trừ việc exclude tuple của nó nên chứa một mục hơn.

Cách làm đẹp hơn trong Python là gì?
Tôi ước tôi không phải viết mã soạn sẵn như model = InternGenericForm.Meta.model cũng dễ bị lỗi.

Trả lời

13
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 
Các vấn đề liên quan