不一樣的Python(10)——objects

1. 每個Python的object都有如下屬性:

(1)一個唯一的id(由函數id()獲得)

(2)一個type(由函數type())獲得)

(3)一些內容

我們不能修改object的id和type。有些object的內容可以修改,有些不行。

http://effbot.org/zone/python-objects.htm有更多的討論。

2. 注意下面的代碼,ID是object的內存地址:

>>> class Point:
...   pass
...
>>> p = Point()
>>> print p
<__main__.Point instance at 0x022D81C0>
>>> print '%x' % (id(p))
22d81c0

3. 模塊copy裏有兩個函數拷貝objects:copy(淺拷貝)和deepcopy(深拷貝)

4. 把一個object轉化爲字符串形式,有兩個函數str()和repr(),它們分別對應__str__和__repr__。這兩個函數的特點:

  • The default implementation is useless (it’s hard to think of one which wouldn’t be, but yeah)
  • __repr__ goal is to be unambiguous
  • __str__ goal is to be readable
  • Container’s __str__ uses contained objects’ __repr__

 更多信息可以參考:http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python

 

發佈了35 篇原創文章 · 獲贊 7 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章