Home

abawchen's graffiti

27 Dec 2017

Python Types and Objects Part 2

Part 1 的文章中,我們先討論到一個 object 到底包含了哪些東西,而接下來我們要討論 object 之間的關係。


先來看一下 <type ‘object’> 和 <type ‘type’>

>>> object
<type 'object'>  #1
>>> type
<type 'type'>    #2
>>> type(object)
<type 'type'>    #3
>>> object.__class__
<type 'type'>    #4
>>> object.__bases__ () #5
>>> type.__class__ <type 'type'> #6
>>> type.__bases__ (<type 'object'>,) #7

#1, #2: object 和 type 是 python 中兩個 primitive(原生)的 object。
#3, #4: 取得 object 的類型,用 type() 和 __class__ 是等價的。
#5: object 是沒有 super-class 的(因為自己是最頂了)
#6: type 的類型是 type(真謎)
#7: type 的 super-class 是 object

而如果要問他們 object 和 type 哪一個先存在,就好像在問 “先有雞,還是先有蛋”,所以可以說他們是同時存在、是相依的。


再用一個例子來解釋 type 和 object 之間的關係:

>>> isinstance(object, object)
True #1
>>> isinstance(type, object)
True #2

#1: 因為 <type ‘type’> 是 <type ‘object’> 的 subclass,所以 <type ‘type’> 的 instance 也是 <type ‘object’> 的 instance (可以說中文嗎) – Dashed Arrow Up Rule
#2: 因為 type 是 metaclass 的 instance,而且 metaclass 是 object 的 subclass(因為 object 是所有 class 的 upser-class,所以 type 也是 object 的 instance. Dashed Arrow Down Rule

Class is Type is Class

如果不知道上面到底說什麼,就記得 Class is Type is Class (for python >=2.3),也就是說 type 和 class 是等意的。(這個結論跳的有點快就是)

我們說過,在 python 中每個東西都是 object,那什麼東西是 type ,什麼東西是 non-type 呢?我們可以用 “只有 type 可以有 subclass” 來做區別,舉例來說 2 是一個 object,但不是 type,因為我們不會說 “2 有 subclass“

總結一下:

  • object 是 type 的 instance
  • object 不是任何東西的 subclass
  • type 是 type 自己的 instance
  • type 是 object 的 subclass
  • python 中只有兩種 object: type 和 non-type,我們用能不能有 subclass 來區別他們。

在下一篇文章會用更多實例來說明 type,class 和 object 之間的關係。


補充:

If X is an instance of A, and A is a subtype of B, then X is an instance of B as well.

– Dash Arrow Up Rule

# Show me the code
>>> class B: pass
>>> class A(B): pass
>>> x = A()
>>> isinstance(x, B)
True

If B is an instance of M, and M is a subclass of A, then B is an instance of A as well.

– Dash Arrow Down Rule

https://stackoverflow.com/a/25205757/9041712 比較容易了解這到底在說什麼。是 python 中有個東西叫做 metaclass,我們可以用 “class 是 metaclass 的 intance” 來理解什麼是 metaclass:

  • M: a metaclass
  • B: an instance of M, i.e., a class
  • A: a subclass of B

Til next time,
abawchen at 08:30