Python名称错误:未定义名称(与具有默认输入参数类型相关)
我有一个问题,就是我正在声明一个函数的输入参数中调用Python名称错误:未定义名称(与具有默认输入参数类型相关),python,python-3.x,arguments,nameerror,Python,Python 3.x,Arguments,Nameerror,我有一个问题,就是我正在声明一个函数的输入参数中调用len(myByteArray)。我希望这是一个默认参数,但Python似乎不喜欢它myByteArray属于bytearray类型。看见我正在访问其内置的find功能(请参阅“bytes.find”) 我的职能: def circularFind(myByteArray, searchVal, start=0, end=len(myByteArray)): """ Return the first-encountered in
len(myByteArray)
。我希望这是一个默认参数,但Python似乎不喜欢它myByteArray
属于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
错误:
NameError:未定义名称“myByteArray”
但是,如果我只删除默认参数(=0
和=len(myByteArray)
),它就可以正常工作。但是…我真的需要那些默认参数,这样start
和end
参数是可选的。我该怎么办
在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
定义函数时会计算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循环查找(myByteArray、searchVal、开始=0、结束=无):
"""
返回在bytearray中遇到的第一个索引,其中searchVal
以递增索引顺序找到,向右搜索,然后
如果索引结束<
索引开始
"""
如果结束为无:
end=len(myByteArray)
#继续做你正在做的事情
def circularFind(myByteArray, searchVal, start=0, end=-1):
if end == -1:
end = len(myByteArray)
#reset of code here.
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