在Python中重写嵌套类成员的更好方法是什么?
我需要“重写”一些基类里面嵌套类的成员,同时保持其他部分不变。
我现在的做法是:
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.Meta
和 InternGenericForm.Meta
完全一样,唯一的不同是它的 exclude
元组里多一个项目。
在Python中,有没有更优雅的方式来做到这一点呢?
我希望不需要写像 model = InternGenericForm.Meta.model
这样的模板代码,因为这也容易出错。
1 个回答
17
当然可以!请看下面的内容:
在编程中,有时候我们需要处理一些数据,这些数据可能来自不同的地方,比如用户输入、文件或者网络请求。为了让程序能够顺利运行,我们需要把这些数据转换成程序能理解的格式。
比如说,如果你从一个网页上获取了一些信息,这些信息可能是以文本的形式存在的。为了让程序能够使用这些信息,我们需要把它们解析成程序能处理的结构,比如列表或者字典。
在这个过程中,我们可能会用到一些工具和库,它们可以帮助我们更轻松地完成这些转换工作。这样,我们就可以专注于编写程序的其他部分,而不必担心数据格式的问题。
总之,处理数据是编程中非常重要的一部分,掌握如何转换和解析数据,会让你的编程之路更加顺畅。
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