Reputation: 670
I have the following class:
classes/helper.py
import json
class Helper:
def uJSONEncode(_, dict):
print(type(_))
return json.dumps(dict).decode('unicode-escape')
I instantiate the class as follows:
Python 2.7.9 (default, Feb 10 2015, 03:28:08)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from classes.helper import Helper
>>> h = Helper()
>>> h.uJSONEncode({"Asd": "asd"})
<type 'instance'>
\u'{"Asd": "asd"}'
Why does python pass (what I assume is) the instantiated object as the first parameter? How would I go around avoiding this behaviour?
Upvotes: 2
Views: 2368
Reputation: 55479
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
Upvotes: 1
Reputation: 251408
You don't need a class just to write a function. Just do this:
def uJSONEncode(mydict):
return json.dumps(mydict).decode('unicode-escape')
You can then import the module containing this function and use it as normal. Wrapping it in a class serves no purpose unless the class is going to actually do something (like store persistent state).
Upvotes: 1
Reputation: 40556
You probably want to create a static method:
class Helper:
@staticmethod
def uJSONEncode(dict):
print(type(_))
return json.dumps(dict).decode('unicode-escape')
and then call it like this:
Helper.uJSONEncode({"Asd": "asd"})
Upvotes: 1