python随笔

上一篇 / 下一篇  2012-01-02 18:43:36 / 个人分类:others

   元旦假期第二天,闲来无事,公司坐坐,记下python随笔(都是基础,路过高手略过:))

question:

one:     isinstance()接受一个类型对象的元
         组做为参数, 这样我们就不必像使用type()时那样写一堆 if-elif-else 判断了。


看完这个表之后,你可能马上冒出一个问题:“等等,你说数值和字符串对象是不可改变的?
看看下面的例子!”:
x = 'Python numbers and strings'
x = 'are immutable?!? What gives?'
i = 0
i = i + 1
“在我看来, 这可不象是不可变对象的行为!” 没错,是这样,不过你还没有搞清楚幕后
的真相。上面的例子中,事实上是一个新对象被创建,然后它取代了旧对象。就是这样,请多
读一遍这段。


>>> a
{1: 2, 2: 3}
>>> a.values()
[2, 3]
>>> x='this'
>>> x
'this'
>>> x[0]
't'
>>> x[0]=p

Traceback (most recent call last):
  File "<pyshell#70>", line 1, in <module>
    x[0]=p
NameError: name 'p' is not defined
>>> x[0]='p'

Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    x[0]='p'
TypeError: 'str' object does not support item assignment
>>> (帮助进一步理解上面的内容)


另一类对象, 列表可以被修改而无须替换原始对象, 看下面的例子:
>>> aList = ['ammonia', 83, 85, 'lady']
>>> aList
['ammonia', 83, 85, 'lady']
>>>
>>> aList[2]
85
>>>
>>> id(aList)
135443480
>>>
>>> aList[2] = aList[2] + 1
>>> aList[3] = 'stereo'
>>> aList
['ammonia', 83, 86, 'stereo']
>>>
>>> id(aList)
135443480(帮忙理解)注意列表的值不论怎么改变, 列表的 ID 始终保持不变



TAG:

testing 引用 删除 xudehua   /   2012-02-25 23:37:53
受教了
 

评分:0

我来说两句

Open Toolbar