As others have mentioned you probably don't need a class here: just put that function as a stand-alone function into your module. Unlike in some other language (eg Java) Python doesn't force you to wrap things up into classes. Even if you have several related functions you probably don't need a class, unless those functions need to share state. Simply putting the related functions into one module is adequate encapsulation.
In Python, normal class methods receive the instance as the first argument. And it's normal to use self
for that argument, so you'd write the method signature like
def uJSONEncode(self, dct):
In Python 2 you should derive your classes from object
so that they're new-style classes, otherwise you get an old-style class, which has some limitations. Eg,
class Helper(object):
In Python 3, classes automatically inherit from object
so you can use the syntax you used in your question, however it's still recommended to use the explicit object
syntax.
One minor benefit of using a new-style class here is that the default representation of the instance's type (i.e., its class) is a little more informative:
import json
class Helper(object):
def uJSONEncode(self, dct):
print(type(self))
return json.dumps(dct).decode('unicode-escape')
h = Helper()
print(h.uJSONEncode({"Asd": "asd"}))
output
<class '__main__.Helper'>
{"Asd": "asd"}
BTW, don't use dict
as a variable name, as that shadows the built-in dict
type, which can lead to mysterious & annoying bugs. The same goes for list
, str
, int
, float
, set
, etc.
Lastly, _
has a special meaning in the interactive interpreter: it's the last result. Demo:
>>> 3+7
10
>>> _
10