Python NameError: 名称未定义(与具有默认输入参数类型有关)

2024-05-29 05:03:19 发布

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

我对我正在声明的函数的输入参数中调用len(myByteArray)这一事实有一个问题。我希望这是一个默认参数,但Python似乎不喜欢它。myByteArray属于bytearray类型。见documentation on bytearray here。我正在访问它内置的find函数,documented here(请参阅“字节.查找"). 在

我的职能:

def circularFind(myByteArray, searchVal, start=0, end=len(myByteArray)):
    """
    Return the first-encountered index in bytearray where searchVal 
    is found, searching to the right, in incrementing-index order, and
    wrapping over the top and back to the beginning if index end < 
    index start
    """
    if (end >= start):
        return myByteArray.find(searchVal, start, end)
    else: #end < start, so search to highest index in bytearray, and then wrap around and search to "end" if nothing was found 
        index = myByteArray.find(searchVal, start, len(myByteArray))
        if (index == -1):
            #if searchVal not found yet, wrap around and keep searching 
            index = myByteArray.find(searchVal, 0, end)
        return index 

尝试使用上述函数的示例:

^{pr2}$

错误:

NameError: name 'myByteArray' is not defined

但是,如果我只删除我的默认参数(=0=len(myByteArray)),它可以正常工作。但是…我真的需要那些默认参数,这样start和{}参数是可选的。我该怎么办?在

在C++中,这将是很容易的,因为在编写函数时指定了参数类型。在


Tags: andtheto函数in参数indexlen
2条回答

定义函数时计算Python默认参数。相反,你想要这样的东西:

def circularFind(myByteArray, searchVal, start=0, end=None):
    """
    Return the first-encountered index in bytearray where searchVal 
    is found, searching to the right, in incrementing-index order, and
    wrapping over the top and back to the beginning if index end < 
    index start
    """
    if end is None:
        end = len(myByteArray)
    # continue doing what you were doing

传递参数时,参数未初始化

>>> def a(b=1,c=b):
...     print(c,b)
... 
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

所以需要将myByteArray的len作为另一个变量发送。在

所以你能做的是

^{pr2}$

相关问题 更多 >

    热门问题