python 2到3转换

2024-06-02 06:46:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,正在尝试将一些供应商提供的代码从python2转换为3。这个函数检查类的一个实例是否已经创建,所以它不会创建一堆新的实例,但是我不确定如何将它转换为Python3。由于pythong2/3中的旧类型和新类型,type类check vs an instance语句尤其需要修改,但我不确定如何修改。非常感谢任何帮助。在

def get_instance(self, classid = "Main", use_cache = TRUE):
    """ Either get the cached logger instance or create a new one

    Note that this is safe, even if you have your target set to sys.stdout
    or sys.stderr
    """

    cache = Logger.cache

    if (type(classid) == ClassType):
        classid = classid.__name__
    elif (type(classid) == InstanceType):
        classid = classid.__class__.__name__

    # classid has to be lowercase, because the ConfigParser returns sections lowercase
    classid = lower(classid)

    if ((cache.has_key(classid)) and (use_cache == TRUE)):
        cat = Logger.cache[classid]
    else:
        instance = Logger.instance

        # test for targets which won't deep copy
        targets = instance.__Logger_targets
        deepcopyable = TRUE
        for i in range(len(targets)):
            if (type(targets[i]) == FileType):
                deepcopyable = FALSE
        if (deepcopyable == FALSE):
            # swap the non-copyable target out for a moment
            del instance.__Logger_targets
            cat = copy.deepcopy(instance)
            instance.__Logger_targets = targets
            cat.__Logger_targets = targets
        else:
            cat = copy.deepcopy(instance)

        cat.__Logger_classname = classid
        # new categories have their own private Nested Diagnostic Contexts
        self.__Logger_ndc = []
        self.__Logger_classid = classid

        cat.debug("Class %s instantiated" % classid)
        if (use_cache == TRUE):
            cache[classid] = cat

    return cat

Tags: theinstanceselftruecacheforifuse
2条回答

打开终端并输入2to3 nameofpythonfile.py,python文件将自动转换。在

如何打开终端

Windows:搜索命令

*nix:类型ctrl-alt-T

if (type(classid) == ClassType):
    classid = classid.__name__
elif (type(classid) == InstanceType):
    classid = classid.__class__.__name__

大致相当于

^{pr2}$

2to3应该能覆盖其余部分

相关问题 更多 >