元组
>>> test=(1 ,2 ,3 ,4 )
>>> len(test)
4
>>> test+(6 ,5 )
(1 , 2 , 3 , 4 , 6 , 5 )
>>> test[0 ]
1
>>> test[3 ]
4
>>> test[0 ]=999
Traceback (most recent call last):
File "<stdin>" , line 1 , in <module>
TypeError: 'tuple' object does not support item assignment
文件
调用内置的open函数创建一个文件对象,以字符串的形式传递给它的一个外部的文件名以及一个处理模式的字符串.
>>> test=open('data.txt' ,'w' )
>>> test.write('Hello\n' )
>>> test.write('world\n' )
>>> test.close()
>>> test=open('data.txt' )
>>> bytes=test.read()
>>> bytes
'Hello\nworld\n'
>>> print bytes
Hello
world
>>> bytes.split()
['Hello' , 'world' ]
文件对象提供了多种读和写的方法(read,readline),预览对象方法可以使用dir(file)
,并可对任何输出的变量名十一欧诺个help.
>>> dir(file)
['__class__' , '__delattr__' , '__doc__' , '__enter__' , '__exit__' , '__format__' , '__getattribute__' , '__hash__' , '__init__' , '__iter__' , '__new__' , '__reduce__' , '__reduce_ex__' , '__repr__' , '__setattr__' , '__sizeof__' , '__str__' , '__subclasshook__' , 'close' , 'closed' , 'encoding' , 'errors' , 'fileno' , 'flush' , 'isatty' , 'mode' , 'name' , 'newlines' , 'next' , 'read' , 'readinto' , 'readline' , 'readlines' , 'seek' , 'softspace' , 'tell' , 'truncate' , 'write' , 'writelines' , 'xreadlines' ]
>>> help(file.name)
open函数能偶实现在python中编写绝大多数文件处理.对于更高级的任务,python的而外的文件类工具:pipes,fifos,sockets,keyed-access,files,对象持久,基于描述符的文件,关系型数据库和面向对象数据库接口
其他核心类型
集合 :通过调用内置set函数而创建的对象的容器.支持数学集合操作:
>>> s=set('spam' )
>>> j=set(['h' ,'a' ,'m' ])
>>> s,j
(set(['a' , 'p' , 's' , 'm' ]), set(['a' , 'h' , 'm' ]))
>>> s&j
set(['a' , 'm' ])
>>> s|j
set(['a' , 'p' , 's' , 'h' , 'm' ])
>>> s-j
set(['p' , 's' ])
十进制数(固定精度浮点数)和布尔值,以及占位符对象None:
>>> reload(decimal)
<module 'decimal' from '/usr/lib/python2.7/decimal.pyc' >
>>> d=decimal.Decimal('3.141' )
>>> d+1
Decimal('4.141' )
>>> 1 >3 ,33 >1
(False , True )
>>> bool("Helloworld" )
True
>>> bool('spam' )
True
>>> bool()
False
>>> x=None
>>> print x
None
>>> test=[None ]* 4
>>> test
[None , None , None , None ]
>>> type(ds)
Traceback (most recent call last):
File "<stdin>" , line 1 , in <module>
NameError: name 'ds' is not defined
>>> type(test)
<type 'list' >
>>> type(type(test))
<type 'type' >
>>> if type(test)==type([]):print 'yes'
...
yes
>>> test
[None , None , None , None ]
>>> if type(test)==list:print 'yes'
...
yes
>>> if isinstance(test,list):print 'yes'
...
yes
用户定义的类:python是面向对象编程(可选但很强大的特性.可以通过支持程序定制而节省开发时间)
>>> class Worker :
... def __init__ (self,name,pay) :
... self.name=name
... self.pay=pay
... def lastName (self) :
... return self.name.split()[-1 ]
... def giveRaise (self,percent) :
... self.pay *= (1.0 + percent)
...
>>> bob = Worker('Bob Smith' ,5000 )
>>> sue=Worker('Sue Jones' ,6000 )
>>> bob.lastName()
'Smith'
>>> sue.lastName()
'Jones'
>>> sue.giveRaise(.10 )
>>> sue.pay
6600.000000000001
>>> sue.giveRaise(.10 )
>>> sue.pay
6600.000000000001
采用”self”对象,一个类中的函数总有一个隐含的对象.类是Python科学的一个特性.