减少Python函数中参数的数量?

2024-09-30 12:30:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是如何处理我使用凯撒密码的那段代码。在

解密和加密函数必须处理字母表的限制(A-Z和A-Z)。我试图在一个名为cycleencrypt的循环函数中为两个字母表编写两个可能的循环。在

但是这个函数需要6个参数,我读过一些不太可读和易懂的地方,在一个函数中有超过3个参数,所以我的问题是:

我是否应该将拆分为两个函数来减少参数的数量,并使代码段更长(但可能更容易理解)? 谢谢你的回答。在

编辑:删除函数周围的docstring以使 我问题的主要目的。在

def offsetctrl(offset):
    while offset < 0:
        offset += 26
    return offset

def cycleencrypt(string, offset, index, listing, first, last):
    offset = offsetctrl(offset)
    if string >= ord(first) and string <= ord(last):
        string += offset
        while string > ord(last):
            string = ord(first) + (string - ord(last) -1)
        listing[index] = chr(string)         

使用许多参数进行加密的循环和控制负偏移量

^{pr2}$

主加密部分,在两行打印中使用多个参数

def decrypt(retezec, offset):
    return encrypt(retezec, -offset)

if __name__ == "__main__":
encrypt("hey fellow how is it going", 5)
decrypt("mjd kjqqtb mtb nx ny ltnsl", 5)

Tags: 函数参数stringindexreturndef字母表offset
3条回答

争论的数量其实并不重要,只要不是一打(也许有人可以链接到你提到的有3个以上的论点,我可能错了)。在

为了在函数定义中更具可读性,请按照docstrings约定编写注释。在

为了在调用函数时更具可读性,在定义中为更有用的值提供尽可能多的默认值(例如,offset默认值为1,索引为0)。在

不管怎样,对于一个长行,使用PEP8准则,它描述了正确跳转行的方法(根据PEP8,行不能超过80个字符)。在

def cycleencrypt(string, offset=1, index=0,
                     listing, first, last):
        """Description

        :param string: description
        :param offset: description
        :param index: description
        :param listing: description
        :param first: description
        :param last: description
        :return description
        """
        offset = offsetctrl(offset)
        if string >= ord(first) and string <= ord(last):
            string += offset
            while string > ord(last):
                string = ord(first) + (string - ord(last) - 1)
            listing[index] = chr(string)    

以下是datetime.datetime的docstring:

class datetime(date):
    """datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
    ...
    """

以及其建造人的签名:

^{pr2}$

我们可以从中学到什么:

  • 添加尽可能多的参数
  • 使用parameters和为参数提供合理的默认值

边想:您认为您的库的用户应该使用cycleencrypt()?您可以将其标记为private(用下划线),这样每个人都会看到它不是一个公共API,他们应该使用encrypt()和{}。在

在这种情况下,最好将代码编写为。类的构造函数可以只接受所需的最小数量的参数(可能根本没有!),然后可以将可选参数设置为类的属性或使用其他方法。在

在设计这样的类时,我发现最有用的方法是首先编写客户端代码也就是说,先编写将使用类的代码,然后从那里向后设计类。在

例如,我可能希望代码看起来像这样:

cypher = Cypher()
cypher.offset = 17
cypher.set_alphabet('A', 'Z')
result = cypher.encrypt('hey fellow how is it going')

希望从这里到Cypher类的设计应该很清楚,但是如果不是,请就堆栈溢出问题提出一个问题!在

如果您想提供encryptdecrypt方便的方法,那么仍然很容易做到。例如,您可以编写如下函数:

^{pr2}$

相关问题 更多 >

    热门问题