簡體   English   中英

為什么`object`是`type`的實例而`type`是`object`的實例?

[英]Why is `object` an instance of `type` and `type` an instance of `object`?

我對object和 Python 3 中的type類有點困惑。也許有人可以澄清我的困惑或提供一些額外的信息。

我目前的理解是,每個 class (除了object )都繼承自一個名為object But every class (including object ) is also an instance of the class type , which is an instance of itself and object and also inherits from object .

我的問題是:

  • 是否有理由/設計決定為什么objecttype的實例並且type繼承自object object 的type /類本身是否也是 object 本身?

  • class ( type )如何成為其自身的實例?

  • 哪一個是真正的基礎 class objecttype
    我一直認為object會是最“基本”的 class,但它似乎是type的一個實例,它是object的一個實例,這是一個 end type的遞歸,...

  • 是否有可能說明object和 class type之間的關系?

我嘗試查找object的條目並type Python 標准庫的文檔。

每個 class(對象除外)都繼承自 object。

>>> for x in object, int, float, str, list, dict:
...     print(f'{x.__name__:6}: {x.__bases__}')
... 
object: ()
int   : (<class 'object'>,)
float : (<class 'object'>,)
str   : (<class 'object'>,)
list  : (<class 'object'>,)
dict  : (<class 'object'>,)

每個 class 都是 class type的實例。

>>> for x in object, int, float, str, list, dict:
...     print(f'{x.__name__:6}: {x.__class__}')
... 
object: <class 'type'>
int   : <class 'type'>
float : <class 'type'>
str   : <class 'type'>
list  : <class 'type'>
dict  : <class 'type'>

type是它自己的一個實例。

>>> type.__class__
<class 'type'>

type也繼承自object

>>> type.__bases__
(<class 'object'>,)

>>> isinstance(object, type)
True
>>> isinstance(type, object)
True
>>> isinstance(type, type)
True
>>> isinstance(object, object)
True
>>> issubclass(type, object)
True
>>> issubclass(object, type)
False

您所有問題的答案都可以在本書中找到: Python 類型和對象

UPD:本書的另一個鏈接 如果它也死了,請告訴我。

回答您的問題的最重要部分:

  • object 的類型/類別本身是否也是 object 本身?

是的,根據第 1 章的規則 1:

“一切都是 object……我們定義的任何類都是對象,當然,這些類的實例也是對象。”

  • 哪一個是真正的基礎 class objecttype

從第 2 章開始:

“這兩個對象是 Python 中的原始對象。我們不妨一次只引入一個,但這會導致雞和蛋的問題——先引入哪個?這兩個對象是相互依賴的——因為它們不能獨立存在它們是相互定義的。”

Luciano Ramalho 在他的“Fluent Python”一書中也說這種關系不能用 Python(第 21 章)來表達:

"The classes object and type have a unique relationship: object is an instance of type, and type is a subclass of object. This relationship is "magic": it cannot be expressed in Python because either class would have to exist before the other could被定義。類型是自身的一個實例這一事實也很神奇。

所以,對於你的問題:

  • class(類型)如何成為其自身的實例?

Luciano 說它也不能用 Python 來表達。

  • 是否有可能說明 object 和 class 類型之間的關系?

非常感謝在第 3 章中制作此插圖的作者:

對象、類型和其他類之間的關系

<class 'type'>是 class object的元類,每個 class (包括type )都直接或間接繼承自object (包括 type )。

如果您需要了解更多關於元類的信息,請點擊此處https://realpython.com/python-metaclasses/

According to Python Data Model , everything in Python is an object and every object has an identity, a type and a value.

object is the base class for all objects, type is also an object, so it is an instance of object , and same for object itself. 同樣type是所有 object 類型的基礎 class ,因此object的類型是type ,並且type本身也是如此。

這是我的理解,如有錯誤歡迎指出。

我意識到它與 Java 中的 instanceKlass 和 _java_mirror 非常相似

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM