[英]Set keyword argument's default value as length of string
我接受了重新創建一些流行的 Python 函數的挑戰,其中一個是string.count()
。 除了 substring 參數和開始索引(可選)之外,它還采用結束索引(也是可選的)。 這是我的代碼:
def count(self,substring,start=0):
self.substring = substring
self.start = start
self.queue = 0
self.counter = 0
for a in self.string[start:]:
if a == self.substring[0]:
self.queue += 1
if a == self.substring[len(self.substring) - 1] and self.queue != 0:
self.queue -= 1
self.counter += 1
return self.counter
我在這個 function: self.string
之外定義了一些變量,這是原始字符串本身。 你可以看到我沒有包括end
的論點,這就是我今天在這里的原因。 我想將參數設置為: end=len(self.string) - 1
,但它只是拋出錯誤並說: NameError: name 'self' is not defined
。 有針對這個的解決方法嗎? 到目前為止,我可以說我的代碼不是問題,因為它可以在沒有參數的情況下完美運行,但我可能錯了。
我認為一個簡單的解決方案如下
def count(self,substring,start=0, end=None):
if end is None:
end = len(self.string) - 1
self.substring = substring
self.start = start
self.end = end # i suppose this needs to be set
self.queue = 0
self.counter = 0
for a in self.string[start:]:
if a == self.substring[0]:
self.queue += 1
if a == self.substring[len(self.substring) - 1] and self.queue != 0:
self.queue -= 1
self.counter += 1
return self.counter
嘗試添加end
是 null 值,然后end = None
在def count()
的括號中:
def count(substring, start = 0, end = None):
# implementation omitted
后來,由於end
的 null 值,您可以在 function 內部創建一個條件,即如果 end 是 null 值,則 end 是-1
。
if end is None: end = len (self.string) - 1
讓我們將參數分為 3 種類型:
substring
)start
、 end
),通常使用None
作為無類型占位符start
, end
)也可以看看:
None
作為默認值end
參數另請參閱IDEone 上的可運行演示:
class StringUtil:
def __init__(self, s):
self.string = s
def count(self, substring, start=0, end=-1): # end index/slice: -1 for the last, instead len(self.substring) - 1
self.substring = substring
self.start = start
self.end = end
self.queue = 0
self.counter = 0
for a in self.string[start:]:
if a == self.substring[0]:
self.queue += 1
if a == self.substring[end] and self.queue != 0: # -1 for the last, instead len(self.substring) - 1
self.queue -= 1
self.counter += 1
return self.counter
sub = "o*o"
s = "Hell" + sub + " W" + sub + "rld"
cnt = StringUtil(s).count(sub)
print(f" counted '{sub}' in '{s}' times: {cnt}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.