2

In what scenarios nested classes are useful, they are used a lot in Django,

class SignUpForm(forms.ModelForm):
    class Meta:
        model = SignUp
        fields = ['full_name','email']

but I think the same can be achieved using other structures,so what do we gain when we use nested classes?

Thanks

  • You may like to refer http://stackoverflow.com/questions/719705/what-is-the-purpose-of-pythons-inner-classes – AlokThakur Feb 08 '16 at 02:46

1 Answers1

0

Django is unusual.

You see, Django makes heavy use of a behind-the-scenes feature called the metaclass. In Python 2, a nested class is the cleanest and most straightforward way of providing the metaclass with information that isn't strictly part of the class itself, such as the model that your form is based on.

In Python 3, it is possible for a metaclass to accept additional keyword arguments, like this:

class Foo(Bar, baz=qux):
    ...

Those arguments are passed directly to the metaclass constructor, and are a much cleaner syntax than the nested class.

I do not know whether Django plans to adopt this syntax, but for backwards compatibility reasons, it is very unlikely the nested class syntax will ever go away entirely.

Community
  • 1
  • 1
Kevin
  • 28,963
  • 9
  • 62
  • 81