递归函数中的泛型参数:可怕的习惯?

2024-09-29 17:23:09 发布

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

我发现自己经常这样做。这个例子很简单,但是在实践中,有很多复杂的赋值来更新数据结构和条件,在这些条件下,第二个递归不会被调用。你知道吗

我正在处理网格数据。点、边和面存储在单独的字典中,大量使用“指针”(dict键)。你知道吗

import itertools

class Demo(object):
    def __init__(self):
        self.a = {}
        self.b = {}
        self.keygen = itertools.count()

    def add_to_b(self, val):
        new_key = next(self.keygen)
        self.b[new_key] = val
        return new_key

    def recur_method(self, arg, argisval=True):
        a_key = next(self.keygen)
        if argisval is True:
            # arg is a value
            b_key = self.add_to_b(arg)
            self.a[a_key] = b_key
            self.recur_method(b_key, argisval=False)
        else:
            # arg is a key
            self.a[a_key] = arg

demo = Demo()
demo.recur_method(2.2)

有更好的办法吗?除了把我所有的作业代码分成七种不同的方法?我应该为此担心吗?你知道吗


Tags: tokeyselfaddnewisdemodef
1条回答
网友
1楼 · 发布于 2024-09-29 17:23:09

试试看

def recur_method(self, key=None, val=None):
    if key is None and val is None:
       raise exception("You fail it")

如果None是有效输入,则使用保护值:

sentinel = object()
def recur_method(self, key=sentinel, val=sentinel):
    if key is sentinel and val is sentinel:
       raise exception("You fail it")

相关问题 更多 >

    热门问题