What are “first class” objects?

前端 未结 5 671
走了就别回头了
走了就别回头了 2020-11-22 16:50

When are objects or something else said to be \"first class\" in a given programming language, and why? In what do they differ from languages where they are not?

EDI

5条回答
  •  礼貌的吻别
    2020-11-22 17:27

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

    Yes.

    Everything in Python is a proper object. Even things that are "primitive types" in other languages.

    You find that an object like 2 actually has a fairly rich and sophisticated interface.

    >>> dir(2)
    ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']
    

    Because everything's a first-class object in Python, there are relatively few obscure special cases.

    In Java, for example, there are primitive types (int, bool, double, char) that aren't proper objects. That's why Java has to introduce Integer, Boolean, Double, and Character as first-class types. This can be hard to teach to beginners -- it isn't obvious why both a primitive type and a class have to exist side-by-side.

    It also means that an object's class is -- itself -- an object. This is different from C++, where the classes don't always have a distinct existence at run-time.

    The type of 2 is the type 'int' object, which has methods, attributes, and a type.

    >>> type(2)
    
    

    The type of a built-in type like int is the type 'type' object. This has methods and attributes, also.

    >>> type(type(2))
    
    

提交回复
热议问题