代码之家  ›  专栏  ›  技术社区  ›  Community wiki

为什么python不允许在函数名和变量名中使用连字符?

  •  29
  • Community wiki  · 技术社区  · 9 月前

    我一直想知道为什么我们不能在python中的函数名和变量名之间使用连字符

    尝试过函数式编程语言,如Lisp和Clojure,其中允许使用连字符。为什么python不这么做。

    # This won't work -- SyntaxError
    def is-even(num):
        return num % 2
    
    # This will work
    def is_even(num):
        return num % 2
    

    我相信圭多爵士这样做一定是出于某些原因。我在谷歌上搜索了一下,但没能找到答案。有人能解释一下吗?

    5 回复  |  直到 3 年前
        1
  •  0
  •   pekowski    3 年前

    因为连字符被用作减法运算符。想象一下你 能够 有一个 is-even 函数,然后您就有了这样的代码:

    my_var = is-even(another_var)
    

    is-even(another_var) 对函数的调用 是偶数 ,还是减去函数的结果 even 来自名为 is ?

    Lisp方言没有这个问题,因为它们使用前缀表示法。例如

    (is-even 4)
    

    (- is (even 4))
    

    在Lisps中。