什么时候对象或其他东西在给定的编程语言中被称为“一流的”,为什么?它们与没有它们的语言有何不同?
当人们说“一切都是对象”时(就像在 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++ 中,函数本身并不是一流的对象:
在 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/