Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a better way of overriding nested class members in Python?

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.

like image 907
Dan Abramov Avatar asked Oct 10 '11 18:10

Dan Abramov


People also ask

What are the advantages disadvantages of nested classes?

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.

How do you override a class in Python?

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.

What is the method overriding in Python?

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.

Can we override a method within the same class in Python?

Therefore, you cannot override two methods that exist in the same class, you can just overload them.


1 Answers

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
like image 74
Cat Plus Plus Avatar answered Sep 23 '22 22:09

Cat Plus Plus