python - 什么是 "first-class"对象?

什么时候对象或其他东西在给定的编程语言中被称为“一流的”,为什么?它们与没有它们的语言有何不同?

当人们说“一切都是对象”时(就像在 Python 中一样),他们真的是指“一切都是一流的”吗?

最佳答案

简而言之,这意味着对对象的使用没有任何限制。这是一样的 任何其他对象。

第一类对象是一个实体,可以动态创建、销毁、传递给函数、作为值返回,并拥有编程语言中其他变量所拥有的所有权利。

Depending on the language, this can imply:

  • being expressible as an anonymous literal value
  • being storable in variables
  • being storable in data structures
  • having an intrinsic identity (independent of any given name)
  • being comparable for equality with other entities
  • being passable as a parameter to a procedure/function
  • being returnable as the result of a procedure/function
  • being constructible at runtime
  • being printable
  • being readable
  • being transmissible among distributed processes
  • being storable outside running processes

Source .

然而,在 C++ 中,函数本身并不是一流的对象:

  • 您可以覆盖“()”运算符,从而可以拥有一个对象函数,这是一等的。
  • 函数指针是一流的。
  • boost bind、lambda 和 function 确实提供一流的功能

在 C++ 中,类不是第一类对象,而是这些类的实例。在 Python 中,类 对象都是第一类对象。 (有关作为对象的类的更多详细信息,请参阅 this answer。

这里是 Javascript 一等函数的例子:

// f: function that takes a number and returns a number
// deltaX: small positive number
// returns a function that is an approximate derivative of f
function makeDerivative( f, deltaX )
{
    var deriv = function(x)
    { 
       return ( f(x + deltaX) - f(x) )/ deltaX;
    }
    return deriv;
}
var cos = makeDerivative( Math.sin, 0.000001);
// cos(0)     ~> 1
// cos(pi/2)  ~> 0

Source .

不是第一类对象的实体称为第二类对象。 C++ 中的函数是二等的,因为它们不能被动态创建。

关于编辑:

EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?

“对象”一词可以随意使用,并不意味着是一流的。将整个概念称为“一流实体”可能更有意义。但在 Python 中,他们的目标是让一切都成为一流的。我相信发表你的言论的人的意图是一流的。

关于python - 什么是 "first-class"对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/245192/

相关文章:

linux - 在管道 grep 到 grep 后保留颜色

bash - 为什么 $$ 返回与父进程相同的 id?

python - 在多个上下文管理器上创建一个 "with" block ?

linux - 使用 Unix 排序对多个键进行排序

python - sum() 之类的函数是什么,但用于乘法?产品()?

python - 在列表中查找属性等于某个值的对象(满足任何条件)

linux - 如何更改 bash 历史完成以完成已经上线的内容?

linux - 否定 bash 脚本中的 if 条件

python - 为什么提早返回比其他方法慢?

python - 使用 groupby 获取组中具有最大值的行