About the Python super function used in django

Asked 2 years ago, Updated 2 years ago, 48 views

As I studied django's class-based view,

When overriding a function, the return value is super(class, self)... There are cases where it goes like this.

No matter how much I look it up, I can't understand the concept of this super function clearly.

If you use super, it is said that calls from the top parent class are made only once if they overlap.

I don't know why I use super because I inherited only one CreateView class that I inherited, so there seems to be no duplication.

I know that the function I encountered is a from_valid function that runs when the form passed from the client is valid.

I know it works if you just paste this code, but I'm return super (ExCreateView, self).I'd like to know the logic of how form_valid(form) works.

class ExCreateView(CreateView):
    def form_valid(self, form):
        # # form.instance.user = self.request.user
        return super(ExCreateView, self).form_valid(form)

I ask for your help.

django

2022-09-21 21:48

1 Answers

In python2, you must hand over your class to super to use the method of the direct parent class immediately. In the form_valid, it seems that it was executed like that to execute all the form_valid defined in the parent in the inheritance process.

Python2 should be like this

class A(object):
   def foo(self):
      print "A"

class B(A):
   def foo(self):
      print "B"    
      super(B, self).foo()

class C(B):
   def foo(self):
      print "C"    
      super(C, self).foo()

c = C()
c.foo()

Python 3 can just do this.

class A(object):
   def foo(self):
      print("A")

class B(A):
   def foo(self):
      print("B")    
      super().foo()

class C(B):
   def foo(self):
      print("C")
      super().foo()

c = C()
c.foo()


2022-09-21 21:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.