2016-08-17 41 views
1

我遇到問題,因爲我正在聲明的函數的輸入參數中調用len(myByteArray)。我希望這是一個默認參數,但Python似乎並不喜歡它。 myByteArraybytearray的類型。見documentation on bytearray here。我正在訪問其內置的find函數,documented here(請參閱「bytes.find」)。Python名稱錯誤:名稱未定義(與具有默認輸入參數類型有關)

我的功能:

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++中,這很容易,因爲參數類型是在編寫函數時指定的。

回答

1

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 
1

在傳遞參數的時候,參數沒有初始化

>>> 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.