I need to “override” some of the base class' nested class members, while keeping the rest intact.
This is what I do:
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
In fact, I want InternApplicationForm.Meta
to be exactly like InternGenericForm.Meta
, except that its exclude
tuple should contain one more item.
What is a more beautiful way of doing this in Python?
I wish I didn't have to write boilerplate code like model = InternGenericForm.Meta.model
that is also prone to errors.
And the benefit of it is you can have less number of objects created at runtime which wouldn't be the case with other types of nested classes. Disadvantage The only disadvantage I can think of is a static nested class has access to both the protected and private members of the outer class.
In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.
Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.
Therefore, you cannot override two methods that exist in the same class, you can just overload them.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With