python函数的可选参数

2024-04-26 04:56:50 发布

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

我试着写一个切片代码,得到一个链表,开始,停止,步骤。 我的代码应该像使用list[start:step:stop]一样。你知道吗

当用户只插入一个参数(假设它是x)时,我的问题就开始了, x应该进入stop而不是start。但是,有人告诉我 参数必须出现在所有参数的末尾。你知道吗

有人能告诉我,在第一个参数的同时,如何只在第二个参数中插入一个输入 一个是强制性的,但第二个不是? 顺便说一下,我不能使用内置函数


Tags: 函数代码用户参数step步骤切片start
3条回答

你可以试试:

def myF(*args):
    number_args = len(args)
    if number_args == 1:
        stop = ...
    elif number_args == 2:
        ...
    elif number_args == 3:
        ...
    else
        print "Error"

*args表示传递给函数myF的参数将存储在变量args中。你知道吗

使用可选(命名)参数:

def foo(start, stop=None, step=1):
    if stop == None:
        start, stop = 0, start
    #rest of the code goes here

然后foo(5) == foo(0,5,1),但是foo(1,5) == foo(1,5,1)。不管怎样,我觉得这很管用。。。:)

您可以编写一个LinkedList类来定义getitem函数来访问python的符号。你知道吗

class LinkedList:

    # Implement the Linked ...

    def __getitem__(self, slice):

        start = slice.start
        stop = slice.stop
        step = slice.step

        # Implement the function

然后你可以随心所欲地使用LinkedList

l = LinkedList()
l[1]
l[1:10]
l[1:10:2]

相关问题 更多 >