Class vs. Type in Python

I just recently started to teach myself how to code. I am currently reading Think Python 2 for python 3 and when it teaches about the type() function, it gives the example type(2) which outputs <class 'int'> . It then states that "the word 'class' is used in the sense of a category; a type is a category of values."

The part that confuses me is that the type() function outputs class instead of type. Also, I'm not sure about the difference between type and class; are string, float point, and integer classes of the type "value", or are they the same thing?

I have looked this up but cannot find an answer to my specific questions or simple enough for me to understand.


Once upon a time, Python had both types and classes. Types were built-in objects defined in C; classes were what you built when using a class statement. The two were named differently because you couldn't mix these; classes could not extend types.

This difference was artificial, a limitation in the language implementation. Starting with Python 2.2, the developers of Python have slowly moved towards unifying the two concepts, with the difference all but gone in Python 3. Built-in types are now also labelled classes, and you can extend them at will.

Your book is trying to explain a difference that isn't present in Python anymore. Even in Python 2 the difference is only there in name, since type(2) shows the word 'type' is still used there:

>>> type(2)
<type 'int'>

but you can subclass int just like any other class.

(Python 2 does still have old-style classes, those that don't inherit from object ; these are a remnant of the old system from before the unification.)


The python hierarchy is Type (Metaclass) -> Class -> Instance. Think of the function type() as going one level up.

If you use the function type() on an instance of an int (any integer) like so: type(123) you will receive the class of the instance which in this case is int . If you will use type() on the class int , you will recieve type type which is the metaclass of int.

Keep in mind metaclasses are advanced technical details of python and you do not need to learn about them at first.

链接地址: http://www.djcxy.com/p/53152.html

上一篇: C语言中的newlib是什么?

下一篇: Python中的类与类型