[英]optional arguments of functions in python
I'm trying to write slicing code which gets a linked list, start,stop, step. 我正在尝试编写切片代码,该切片代码获得了链表,开始,停止,步骤。 My code is supposed to behave like same as using list[start:step:stop]
. 我的代码的行为应与使用list[start:step:stop]
。
My problem starts when the user insert only 1 argument (let's says it was x ) - then, x is supposed to get into stop
and and not start
. 当用户仅插入1个参数(让我们说它是x )时,我的问题就开始了-然后, x应该进入stop
而不是start
。 But, I have been told that optional arguments need to appear at the end of all the arguments. 但是,有人告诉我,可选参数必须出现在所有参数的末尾。
Can someone tell me how can we insert only 1 input to the second argument while the first one is mandatory but the second one is not? 有人可以告诉我如何在第二个参数中仅插入1个输入,而第一个参数是强制性输入而第二个不是强制性输入吗? By the way, i can't use built-in functions 顺便说一句,我不能使用内置功能
You could write a LinkedList class that defines the __ getitem __ function to get access to python's notation. 您可以编写一个定义__ getitem __函数的LinkedList类来访问python的符号。
class LinkedList:
# Implement the Linked ...
def __getitem__(self, slice):
start = slice.start
stop = slice.stop
step = slice.step
# Implement the function
Then you can use LinkedList like you want 然后,您可以根据需要使用LinkedList
l = LinkedList()
l[1]
l[1:10]
l[1:10:2]
You could try: 您可以尝试:
def myF(*args):
number_args = len(args)
if number_args == 1:
stop = ...
elif number_args == 2:
...
elif number_args == 3:
...
else
print "Error"
*args
means that the arguments passed to the function myF
will be stored in the variable args
. *args
表示传递给函数myF
的参数将存储在变量args
。
Using optional (named) arguments: 使用可选的(命名的)参数:
def foo(start, stop=None, step=1):
if stop == None:
start, stop = 0, start
#rest of the code goes here
Then foo(5) == foo(0,5,1)
, but foo(1,5) == foo(1,5,1)
. 然后foo(5) == foo(0,5,1)
,但是foo(1,5) == foo(1,5,1)
。 I think this works, anyway... :) 我认为无论如何... :)
def func(arg1=None, arg2=None, arg3=None):
if not arg1:
print 'arg1 is mandatory'
return False
## do your stuff here
arg1 = 1
arg2 = 4
arg3 = 1
## works fine
func(arg1=arg1, arg2=arg2, arg3=arg3)
## Evaluated as False, Since the first argument is missing
func(arg2=arg2, arg3=arg3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.