[英]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.