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 {}

Bình Ông
  • 96
  • 7
  • 1
    `self` means instance of class which you do not have for static method. Instead use class name i.e. `Utils.checkRequestIsOk()` – Marcin Orlowski May 19 '22 at 13:51
  • Or make your method a `@classmethod` instead, and use `cls.checkRequestIsOkay`. – khelwood May 19 '22 at 13:54
  • note class method and static method are not equivalent. See https://stackoverflow.com/questions/136097/difference-between-staticmethod-and-classmethod – Marcin Orlowski May 19 '22 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. – wwii May 19 '22 at 14:20

1 Answers1

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 {}
Phantoms
  • 145
  • 5