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

时间:2015-09-27 06:21:46

标签: python

我有以下课程:

classes/helper.py

import json

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

我按如下方式实例化该类:

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传递(我假设是)实例化对象作为第一个参数?我该如何避免这种行为呢?

3 个答案:

答案 0 :(得分:1)

您可能想要创建一个静态方法:

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

然后像这样调用它:

Helper.uJSONEncode({"Asd": "asd"})  

答案 1 :(得分:1)

正如其他人提到的那样,你可能需要一个类:只需将该函数作为独立函数放入模块中。与其他语言(例如Java)不同,Python不会强迫您将内容包装到类中。即使你有几个相关的函数,你可能不需要一个类,除非这些函数需要共享状态。简单地将相关功能放入一个模块就足够了。

在Python中,普通类方法接收实例作为第一个参数。对该参数使用self是正常的,因此您可以像

一样编写方法签名
def uJSONEncode(self, dct):


在Python 2中,您应该从object派生您的类,以便它们是new-style classes,否则您会得到一个旧式类,这有一些限制。例如,

class Helper(object):

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

在这里使用新式类的一个小好处是实例类型的默认表示(即它的类)提供了更多信息:

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"}))

<强>输出

<class '__main__.Helper'>
{"Asd": "asd"}


顺便说一句,不要使用dict作为变量名称,因为它会影响内置的dict类型,这会导致神秘的&amp;恼人的错误。 liststrintfloatset等也是如此。


最后,_在交互式解释器中具有特殊含义:它是最后的结果。演示:

>>> 3+7
10
>>> _
10

答案 2 :(得分:1)

只需编写一个函数就不需要一个类。就这样做:

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

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