gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:12 31 4
gpt4 key购买 nike

我有以下类(class):

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

最佳答案

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

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

然后您可以导入包含此函数的模块并正常使用它。将它包装在一个类中没有任何意义,除非该类将实际执行某些操作(例如存储持久状态)。

关于Python 导入类作为实例化对象传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32805178/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com