Home > Back-end >  How to call other methods in a class in django when self is not supplied as an argument
How to call other methods in a class in django when self is not supplied as an argument

Time:08-11

I come from PHP/Laravel Background where for calling methods or accessing properties within a class ,use of $this keyword is sufficient.In python3/Django4.0.6 i have to use request as first parameter to capture the request body for eg.

class CustomAuth:

      def verifyToken(token):
          pass

      def login(request):
          data = request.body
          # how do i call verifyToken?
          # if i use self as first argument then i am not able to access the request

CodePudding user response:

This would be relatively standard based on what you are asking:

class CustomAuth:

      def verifyToken(self, token):
          self.token = token
        

      def login(self, request):
            self.request = request
            data = request.body

            
            # how do i call verifyToken?
            x = self.verifyToken(self.token)
            # if i use self as first argument then i am not able to access the request
            r = self.request


Also, note the comments suggesting the @staticmethod method as an alternative.

CodePudding user response:

The point of "self" is to link the functions and variables to the instance. If your function don't use class internal variables or other function you can decorate with @staticmethod and you will access it as usual.

For more details google it. https://www.w3schools.com/python/gloss_python_self.asp#:~:text=The self parameter is a,that belongs to the class.

I find it strange the way you use the class. Why don't you instantiate with parameter token, and don't need to use the function to assign token to internal class variable.

  • Related