0

I just start using Python to create new project but I have problems about Class, Static Method in Python.

I want to create a Utils class that I can call from other place so I create this class below but I can not call other function in this class without self

import json
class Utils:
 @staticmethod
 def checkRequestIsOkay(requestResponse):
 if(len(requestResponse.text) > 0):
 return True
 else:
 return False
 @staticmethod
 def getDataFromJson(requestResponse):
 if checkRequestIsOkay(requestResponse):
 return json.loads(requestResponse.text)
 else:
 return {}
asked May 19, 2022 at 13:48
4
  • 1
    self means instance of class which you do not have for static method. Instead use class name i.e. Utils.checkRequestIsOk() Commented May 19, 2022 at 13:51
  • Or make your method a @classmethod instead, and use cls.checkRequestIsOkay. Commented May 19, 2022 at 13:54
  • note class method and static method are not equivalent. See stackoverflow.com/questions/136097/… Commented May 19, 2022 at 13:56
  • You haven't shown how you are using or want to use the class. Often with python a module is use to contain utility functions instead of using a class - the concept is the same, put the functions in a module then import the module and call them with modulename.func(), or just import individual functions from the module. Commented May 19, 2022 at 14:20

1 Answer 1

1

Don't use self. You need to use class name.

@staticmethod
def getDataFromJson(requestResponse):
 if Utils.checkRequestIsOkay(requestResponse):
 return json.loads(requestResponse.text)
 else:
 return {}
answered May 19, 2022 at 13:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.