不一样的Python(10)——objects

来源:互联网 发布:java实现oracle jdbc 编辑:程序博客网 时间:2024/05/21 22:47

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