Python中F(x)和F x之间的差异

ali*_*oar 4 python

在Python中,可以调用del x或者del(x).我知道如何定义一个名为F(x)的函数,但我不知道如何定义一个名为cal的函数del,没有元组作为参数.

F x和之间的区别是什么F(x),如何定义一个可以在没有括号的情况下调用的函数?

>>> a = 10
>>> a
10
>>> del a             <------------ can be called without parenthesis
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> a = 1
>>> del (a)
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> def f(x): 1
... 
>>> f (10)
>>> print f (10)
None
>>> def f(x): return 1
... 
>>> print f (10)
1
>>> f 1                  <------   cannot be called so
  File "<stdin>", line 1
    f 1
      ^
SyntaxError: invalid syntax
>>> 
Run Code Online (Sandbox Code Playgroud)

Roc*_*key 9

主要原因是它del实际上是一个语句,因此在Python中有特殊的行为.因此,您实际上无法自己定义这些(和此行为)* - 它是一组保留关键字的语言的内置部分.

**我想你可能会编辑Python本身的源代码并构建自己的源代码,但我不认为这就是你所追求的:)*

  • @alinsoar - 你不能.`statements`内置于语言中,无法创建(或覆盖). (2认同)