Python NameError: name is not defined (related to having default input argument types)

Python NameError: name is not defined (related to having default input argument types)

我在声明函数的输入参数中调用 len(myByteArray) 时遇到问题。我希望这是默认参数,但 Python 似乎不喜欢它。 myByteArraybytearray 类型。参见 documentation on bytearray here. I am accessing its built-in find function, documented here(参见 "bytes.find")。

我的函数:

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 

尝试使用上述功能的示例:

#-------------------------------------------------------------------
#EXAMPLES:
#-------------------------------------------------------------------
#Only executute this block of code if running this module directly,
#*not* if importing it
#-see here: http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm
if __name__ == "__main__": #if running this module as a stand-alone program
    import random
    random.seed(0)

    bytes = bytearray(100)
    for i in range(len(bytes)):
        bytes[i] = int(random.random()*256)

    print(list(bytes)); print();

    print('built-in method:')
    print(bytes.find(255))
    print(bytes.find(2,10,97))
    print(bytes.find(5,97,4))

    print('\ncircularFind:')
    print(circularFind(bytes,255))
    print(circularFind(bytes,2,10,97))
    print(circularFind(bytes,5,97,4))

错误:

NameError: name 'myByteArray' is not defined

如果我只是删除我的默认参数(=0=len(myByteArray)),但是,它工作正常。但是......我真的想要那些默认参数,以便 startend 参数是可选的。我该怎么办?

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

传递参数时,参数没有初始化

>>> 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 作为另一个变量发送。

所以你可以做的是,

def circularFind(myByteArray, searchVal, start=0, end=-1):
    if end == -1:
        end = len(myByteArray)
    #reset of code here.

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