Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to generically apply an override of a function to mutiple classes in python?
    text
    copied!<p>I am working on a Django application but this seems like it is just a python question, with nothing necessarily specific to Django. I'm pretty new to python, and its hard to describe what I am trying to do, but easier to show so here goes:</p> <p>I have one class:</p> <pre><code>class SlideForm(ModelForm): class Meta: model = Slide </code></pre> <p>which I subclass:</p> <pre><code>class HiddenSlideForm(SlideForm): def __init__(self, *args, **kwargs): super(HiddenSlideForm, self).__init__(*args, **kwargs) for name, field in self.fields.iteritems(): field.widget = field.hidden_widget() field.required = False </code></pre> <p>and then I have another class:</p> <pre><code>class DeckForm(ModelForm): def __init__(self, *args, **kwargs): # do some stuff here return super(DeckForm, self).__init__(*args, **kwargs) class Meta: model = Deck # other stuff here </code></pre> <p>which I also sub-class:</p> <pre><code>class HiddenDeckForm(DeckForm): def __init__(self, *args, **kwargs): super(HiddenDeckForm, self).__init__(*args, **kwargs) for name, field in self.fields.iteritems(): field.widget = field.hidden_widget() field.required = False </code></pre> <p>Note that the subclasses have the exact same code other than class names and do the exact same thing. I have been trying to figure what the best way to genericize this so I can keep it DRY and easily use it for other classes, and have considered decorators and/or multiple inheritance--both of which are new concepts for me--but I keep getting mixed up. </p> <p>Help is appreciated!</p> <p>(As a side note, feel free to point out any problems you see in my django code :) )</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload