Python Type System - Object vs Type

2019-02-09 11:02发布

I am new to Python. I am familiar with Java, C/C++, and OCaml. I understand Lambda Calculus and elementary Type Theory because of a Programming Languages course I took at University.

Armed with this background, I tried to read this - http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html

Somewhere down, he mentions this:

  • (type 'object') is an instance of (type 'type')
  • (type 'object') is a subclass of no object.
  • (type 'type') is an instance of itself.
  • (type'type') is a subclass of (type 'object')

I am not able to wrap my poor brain around this:

  • (type 'object') is an instance of (type 'type')
  • (type 'type') is a subclass of (type 'object')

What the bleep is happening here? What I want to hear is extremely in depth reasons on what exactly is happening here, and why things are the way they are. No shallow reasons or analogies please.

2条回答
甜甜的少女心
2楼-- · 2019-02-09 11:26

It is talking specifically about the object type. For type, all types inherit from <type 'type'>.

I believe the other statement is just pointing out that <type 'type'> is an object; an example I thought of from looking further down:

t = list.__class__ # <type 'type'>
t.__bases__ # (<type 'object'>,)
查看更多
3楼-- · 2019-02-09 11:26

Because the notion of type is the same as class you can subclass type with normal object-oriented techniques and class syntax to customize it.

And because classes are really instances of the type class, creating classes from customized subclasses of type allows to implement custom kinds of classes.

In new-style classes:

  • type is a class that generates user-defined classes.
  • Metaclasses are subclasses of the type class.
  • Class objects are instances of the type class, or a subclass thereof.
  • Instance objects are generated from a class.
查看更多
登录 后发表回答