在Python中,是否可以在不引发异常的情况下拥有上述代码?

def myfunc():
    pass

# TypeError myfunc() takes no arguments (1 given)
myfunc('param')

通常在PHP中,在某些情况下,我启动一个没有参数的函数,然后检索函数内部的参数。
实际上,我不想在myfunc中声明参数,然后向它传递一些参数。我找到的唯一解决方案是myfunc(*arg)。还有其他方法吗?

最佳答案

>>> def myFunc(*args, **kwargs):
...   # This function accepts arbitary arguments:
...   # Keywords arguments are available in the kwargs dict;
...   # Regular arguments are in the args tuple.
...   # (This behaviour is dictated by the stars, not by
...   #  the name of the formal parameters.)
...   print args, kwargs
...
>>> myFunc()
() {}
>>> myFunc(2)
(2,) {}
>>> myFunc(2,5)
(2, 5) {}
>>> myFunc(b = 3)
() {'b': 3}
>>> import dis
>>> dis.dis(myFunc)
  1           0 LOAD_FAST                0 (args)
              3 PRINT_ITEM
              4 LOAD_FAST                1 (kwargs)
              7 PRINT_ITEM
              8 PRINT_NEWLINE
              9 LOAD_CONST               0 (None)
             12 RETURN_VALUE

实际上回答这个问题:不,我不相信还有其他的方法。
主要原因很简单:c python是基于堆栈的。不需要参数的函数将不会在堆栈上为其分配空间(myFunc,相反,它们位于位置0和1)。(见注释)
另外一点是,您如何访问参数,否则呢?

关于python - 是否可以声明一个没有参数的函数,但是然后将一些参数传递给该函数而不引发异常?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2241200/

10-11 23:16
查看更多