我对我打电话的事实有疑问len(myByteArray)
在我声明的函数的输入参数中。我希望它成为默认参数,但 Python 似乎不喜欢它。myByteArray
属于类型bytearray
. See 关于 bytearray 的文档在这里。我正在访问它的内置find
功能,记录在这里(参见“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))
Error:
NameError:名称“myByteArray”未定义
如果我只是删除我的默认参数(=0
and =len(myByteArray)
),但是,它工作得很好。但是......我真的想要那些默认参数,以便start
and end
参数是可选的。我该怎么办?
在 C++ 中,这很容易,因为参数类型是在编写函数时指定的。