python导入的类作为实例化对象传递

Python imported class being passed as instantiated object

我有以下课程:

classes/helper.py

1
2
3
4
5
6
import json

class Helper:
    def uJSONEncode(_, dict):
        print(type(_))
        return json.dumps(dict).decode('unicode-escape')

我将类实例化如下:

1
2
3
4
5
6
7
8
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"}'

为什么python(我假设是)将实例化的对象作为第一个参数传递?我该如何避免这种行为?


You don't need a class just to write a function. Just do this:

1
2
def uJSONEncode(mydict):
    return json.dumps(mydict).decode('unicode-escape')

然后,您可以导入包含此函数的模块并正常使用它。把它包装在一个类中是没有用的,除非该类实际上要做一些事情(比如存储持久状态)。


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

1
def uJSONEncode(self, dct):

在python 2中,您应该从object派生类,以便它们是新样式的类,否则您会得到一个旧样式的类,这有一些限制。如,

1
class Helper(object):

在python 3中,类自动从object继承,因此您可以使用问题中使用的语法,但是仍然建议使用显式object语法。

在这里使用一个新样式的类的一个小好处是,实例类型(即其类)的默认表示形式更具信息性:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
<p><center>[wp_ad_camp_1]</center></p><hr><P>您可能想要创建一个静态方法:</P>[cc lang="
python"]class Helper:
    @staticmethod
    def uJSONEncode(dict):
        print(type(_))
        return json.dumps(dict).decode('unicode-escape')

然后这样称呼它:

[cc lang="python"]Helper.uJSONEncode({"Asd":"asd