简体   繁体   English

将关键字参数的默认值设置为字符串的长度

[英]Set keyword argument's default value as length of string

I've taken up a challenge to recreate some popular Python functions, one of them being string.count() .我接受了重新创建一些流行的 Python 函数的挑战,其中一个是string.count() Other than the substring argument and the start index (optional), it also takes the end index (optional as well).除了 substring 参数和开始索引(可选)之外,它还采用结束索引(也是可选的)。 This is my code:这是我的代码:

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

Some variables I have defined outside of this function: self.string , which is the original string itself.我在这个 function: self.string之外定义了一些变量,这是原始字符串本身。 You can see that I have not included the end argument, and that is why I'm here today.你可以看到我没有包括end的论点,这就是我今天在这里的原因。 I would like to set the argument as: end=len(self.string) - 1 , but it just throws and error and says: NameError: name 'self' is not defined .我想将参数设置为: end=len(self.string) - 1 ,但它只是抛出错误并说: NameError: name 'self' is not defined Is there a solution to this?有针对这个的解决方法吗? So far I can say that my code is not the problem, since it works perfectly without the argument, but I may be wrong.到目前为止,我可以说我的代码不是问题,因为它可以在没有参数的情况下完美运行,但我可能错了。

I think one simple solution is the following我认为一个简单的解决方案如下

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

Try adding that end is a null value, then end = None in parentheses of def count() :尝试添加end是 null 值,然后end = Nonedef count()的括号中:

def count(substring, start = 0, end = None):
    # implementation omitted

Later, thanks to the null value of end , you can create a condition inside the function, that is, if end is a null value, then end is -1 .后来,由于end的 null 值,您可以在 function 内部创建一个条件,即如果 end 是 null 值,则 end 是-1

You can write if end is None: end = len (self.string) - 1 if end is None: end = len (self.string) - 1

Let's categorize parameters into 3 types:让我们将参数分为 3 种类型:

  • required (positional) parameter (like substring )必需的(位置)参数(如substring
  • optional parameter (like start , end ), often with None as type-less placeholder可选参数(如startend ),通常使用None作为无类型占位符
  • parameter with default argument values (like start , end )具有默认参数值的参数(如startend

See also:也可以看看:

Use slicing and default for end parameter使用切片和默认end参数

See also the runnable demo on IDEone :另请参阅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.

相关问题 默认情况下,将参数设置为等于另一个参数的值 - Set argument equal to another argument's value by default 机器人框架:创建一个带有可选参数的关键字。 参数的默认值应该来自脚本 - Robot framework: create a keyword with optional argument. The argument's default value should come from a script 在 Python 中,将参数的默认值设置为函数是一种糟糕的形式吗? - In Python, is it bad form to set an argument's default value to be a function? 将关键字参数传递给关键字具有默认值的另一个函数 - Pass keyword argument to another function where the keyword has a default value 如何将Argparse参数的默认值设置为位置参数的值? - How do I set an Argparse argument's default value to a positional argument's value? python 中关键字参数值的命名空间是什么? - What is a keyword argument value's namespace in python? 使用 function 返回值作为关键字参数默认值是否可以接受? - Is it acceptable to use a function return value as a keyword argument default value? Function 关键字作为默认参数 - Function with keyword as default argument 是否可以基于其他可选参数将argparse的可选参数设置为默认值? - Is it possible to set argparse's optional argument to a default value based on other optional argument? ClearDB默认连接字符串上的reconnect关键字参数导致MySQLdb错误 - reconnect keyword argument on ClearDB default connection string causing errors with MySQLdb
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM