在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?

请每个回答只回答一个特征。


当前回答

试试吧,除非,否则

try:     pass
except:  pass
else:    pass
finally: pass

如果没有捕获异常,则执行else部分。

有道理,但一开始我真的不知道它是干什么的。

例子:

def show_square(string):
  try:
    n = int(string, 10)
  except ValueError:
    print "I can't do that, Dave."
  else:
    print n * n

其他回答

在C:

int main() {
  int i = 0;
  int array[] = {1,2};

  return (i[array] + 1 == array[i]);
}

这个程序将返回1 (true)。

在JavaScript中,方法的结果取决于所放置的样式花括号。这是K&R风格,其中括号放在方法签名之后和return语句之后:

var foo = function() {
  return {
    key: 'value'
  };
}

foo() // returns an object here

现在,如果我将这段代码格式化为Allman风格,其中括号总是放在新行上,结果是不同的:

var foo = function()
{
  return
  {
    key: 'value'
  };
}

foo() // returns undefined here

如何来吗?在JavaScript中,如果您不自己做,语言会自动在每行末尾放置分号。所以在最后一个代码片段中真正发生的是这样的:

var foo = function()
{
  return; // here's actually a semicolon, automatically set by JavaScript!
  {
    key: 'value'
  };
}

因此,如果调用foo(),方法中的第一个语句将是一个返回语句,该语句将返回undefined,并且不会执行后面的其他语句。

Delphi不关心像“word”这样的类型转换,将读取数组arr[0..65535] where pos = 65535: Arr[单词(pos + 10)]

当今所有语言:

TypeA a = (TypeA)some_operation_returning_TypeB(1,2,3); // TypeB is not inheriting TypeA

在运行时失败,并带有"Cast to TypeA failed exception"-消息(或类似消息)。这告诉我们程序员到底有多懒。他们没有办法产生消息“未能将TypeA的变量‘a’与TypeB的值‘some_operation_returning_TypeB(1,2,3)’赋值”。他. .他们的座右铭是“犯错误的人必须受苦”。

有趣的自动装箱和Java中的整数缓存:

Integer foo = 1000;
Integer bar = 1000;

foo <= bar; // true
foo >= bar; // true
foo == bar; // false

//However, if the values of foo and bar are between 127 and -128 (inclusive)
//the behaviour changes:

Integer foo = 42;
Integer bar = 42;

foo <= bar; // true
foo >= bar; // true
foo == bar; // true

解释

快速浏览一下Java源代码将会出现以下内容:

/**
 * Returns a <tt>Integer</tt> instance representing the specified
 * <tt>int</tt> value.
 * If a new <tt>Integer</tt> instance is not required, this method
 * should generally be used in preference to the constructor
 * {@link #Integer(int)}, as this method is likely to yield
 * significantly better space and time performance by caching
 * frequently requested values.
 *
 * @param  i an <code>int</code> value.
 * @return a <tt>Integer</tt> instance representing <tt>i</tt>.
 * @since  1.5
 */
public static Integer valueOf(int i) {
    if (i >= -128 && i <= IntegerCache.high)
        return IntegerCache.cache[i + 128];
    else
        return new Integer(i);
}

注意:IntegerCache。High默认为127,除非由属性设置。

自动装箱的情况是,foo和bar都是从缓存中检索到相同的整数对象,除非显式创建:例如,foo = new integer(42),因此在比较引用是否相等时,它们将为真而不是假。比较Integer值的正确方法是使用.equals;