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 ÔngBình Ông
asked May 19, 2022 at 13:48
1 Answer 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 {}
Comments
lang-py
self
means instance of class which you do not have for static method. Instead use class name i.e.Utils.checkRequestIsOk()
@classmethod
instead, and usecls.checkRequestIsOkay
.modulename.func()
, or just import individual functions from the module.