首頁  >  文章  >  後端開發  >  關於Python的object和type詳細介紹

關於Python的object和type詳細介紹

高洛峰
高洛峰原創
2017-03-20 11:25:311856瀏覽

1、節選自Python Documentation 3.5.2的部分解釋

Objects are Python's abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann's model# of a “stored program computer,” code is also represented by objects.)

物件是Python對資料的抽象化。 Python程式中的所有資料都由物件或物件之間的關係表示。 (在某種意義上,並且符合馮諾依曼的「儲存程式電腦」的模型,程式碼也由物件表示的)。

Every object has an identity, a type and a value. An object's identity never changes once it has been created; you may think of it as the object's address in memory. The 'is' operator compares the identity of two objects; the id() function returns an integer representing its identity.

每個物件都有一個標識,一個型別和一個值。 物件的身份一旦創建就不會改變; 你可以把它看作記憶體中的物件位址。 'is'運算子比較兩個物件的識別; id()函數傳回一個表示其身分的整數。

An object's type determines the operations that the object supports (e.g., “does it have a length?”) and also defines the possible values for objects of that type. The type() function returns type(obects types. which is an object itself). Like its identity, an object's type is also unchangeable.

物件的類型決定物件支援的操作(例如,「它有長度嗎?」),並且還定義該類型物件的可能值。 type()函數傳回一個物件的型別(它是一個物件本身)。與它的身分一樣,物件的類型也是不可改變的。

2、Pyhtml的解釋:

object:

class object
      The most base type

type:

class type(object)
      type(object_or_name, bases, dict)
      type(object) -> the object's type
      type(name, bases, dict) -> a new type

關於Python的object和type詳細介紹

#從上面三個圖可以看出,物件obeject是最基本的型別type,它是一個整體性的對資料的抽象概念。相對於物件object而言,型別type是一個稍微具體的抽象概念,說它具體,是因為它已經有從物件object細化出更具體抽象概念的因子,這就是為什麼type(int)、type(float)、type(str)、type(list)、type(tuple)、type(set)等等的型別都是type,這也是為什麼instance(type, object)和instance(object, type)都為True的原因,即類型type是作為int、float等類型的整體概念而言的。那麼,為什麼issubclass(type, object)為True,而issubclass(object, type)為Flase呢?從第二張圖,即從繼承關係可以看到,type是object的子類,因此前者為True,後者為False。若從Python語言的整體設計來看,是先有對象,後有相對具體的類型,即整體優先於部分的設計思想。

如果從更本質的視角去看待這些問題的話,就要從Python Documentation-->3. Data Model-->3.1 Objects,values and types找原因了[請參考Python官方標準函式庫],從標準函式庫裡可以看到:

  • object是Python對資料的抽象,它是Python程式對資料的集中體現。

  • 每個物件都有一個標識,一個型別和一個值。

  • 物件的類型決定物件支援的操作。

  • 某些物件的值可以變更。 其值可以改變的物件稱為可變物件;物件的值在建立後不可變更的物件稱為不可變物件。

因此,從Python整體設計系統來看的話,就是先有對象,再有標識、類型和值,接著是對對象的操作等等,這也就解釋了圖3的結果形成的原因了。

 

以上是關於Python的object和type詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn