现在的位置: 首页 > 综合 > 正文

Python学习小笔记2

2014年01月24日 ⁄ 综合 ⁄ 共 7266字 ⁄ 字号 评论关闭

1.字典是可变的,如果你想修改字典,并且保留原来的备份,就要用到字典的copy方法。
 可以用字典表示矩阵。
>>> matrix={(0,3):1,(2,1):2,(4,3):3}
>>> #用这种方法,我们不能得到值为零的元素,因为这个矩阵中,没有零值的键
>>> matrix[2,1]
2
>>> matrix[(2,1)]
2
>>> matrix[1,3]

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    matrix[1,3]
KeyError: (1, 3)
>>> matrix.get((1,3),0)
0
>>> matrix
{(0, 3): 1, (4, 3): 3, (2, 1): 2}
>>> matrix[1,3]

Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    matrix[1,3]
KeyError: (1, 3)
>>>
2.python用一种叫做长整数的类型处理任意大小的整数。通常我们用整数后面加一个大写的L表示长整数。
3.文件的打开和关闭
>>> f=open("D://test.txt","w")                                    #以写的方式在D盘创建一个名为“test.txt”的文件,并创建对象赋给f
>>> f.write("This is the best time ,and the worst one/n")
>>> f.write("Now close the file")
>>> f.close()
>>> f=open("D://test.txt","r")
>>> text=f.read()                                                 #read可以接受数字参数,表示读出一定数量的字符。如果读到文件的末尾,就返回空字符
>>> print text
This is the best time ,and the worst one
Now close the file
>>>
>>> f=open("txt.txt","r")                                         #如果以读的方式打开一个不存在的文件,则解释器会报错

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    f=open("txt.txt","r")
IOError: [Errno 2] No such file or directory: 'txt.txt'
>>>
>>> f=open("D://test.dat","w")
>>> f.write("I love Python/nHello, world/nGood Bye!/n")     #write的参数只能是字符串,如果想把其他类型的变量写入文件,就必须将其转换为字符串。
>>> f.close()
>>> f=open("D://test.dat","r")
>>> print f.readline()
I love Python

>>> print f.readlines()
['Hello, world/n', 'Good Bye!/n']
>>> print f.readline()

>>> print f.readlines()
[]
>>>
4.为了将不同类型的数据保存到文件,必须将其转换成字符串。结果导致从文件读的一切内容都是字符串,数据的原始类型信息丢失了。解决的办法是输入pickle模块,用它提供的方法把各种类型的数据存入文件,数据结构的信息也被保存了。也就是说你保存了什么,将来读出的还是什么。
>>> import pickle
>>> f=open("D://test.dat","w")
>>> pickle.dump(100,f)
>>> pickle.dump(123.98,f)
>>> pickle.dump((1,3,"abc"),f)
>>> pickle.dump([4,5,7],f)
>>> f.close
<built-in method close of file object at 0x00AFBB60>
>>> f.close()
>>> f=open("D://test.dat","r")
>>> a=pickle.load(f)
>>> print a
100
>>> type(a)
<type 'int'>
>>> b=pickle.load(f)
>>> print b
123.98
>>> type(b)
<type 'float'>
>>> c=pickle.load()
>>> c=pickle.load(f)
>>> print c
(1, 3, 'abc')
>>> type(c)
<type 'tuple'>                           #序列
>>> d=pickle.load(f)
>>> print d
[4, 5, 7]
>>> type(d)
<type 'list'>                            #列表
>>>
5.程序在执行的过程中产生异常,但不希望程序终止执行,这时就需要用try和except语句对异常进行处理。异常信息分为两个部分,冒号前面的是异常类型,之后是对此的简单说明。其他的信息则指出在程序的什么地方出错了。
#自定义异常
filename=''
while 1:
    filename=raw_input("Input a file name:")
    if filename=='q':
        break
    try:
        f=open(filename,"r")
        print 'Opened a file'
        f.close()
    except:
        print 'There is no file named ',filename

如果程序检测到错误,我们也可以定义用raise抛出异常
>>> def inputAge():
    age=input("Input your age:")
    if(age>100 or age<18):
        raise 'BadNumberError','out of range'       #抛出异常
    return age

>>> inputAge()
Input your age:20
20
>>> inputAge()
Input your age:12

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    inputAge()
  File "<pyshell#1>", line 4, in inputAge
    raise 'BadNumberError','out of range'
BadNumberError: out of range
>>> inputAge()
Input your age:101

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    inputAge()
  File "<pyshell#1>", line 4, in inputAge
    raise 'BadNumberError','out of range'
BadNumberError: out of range
>>>
while 1:
    try:
        x=int(raw_input("Input a number:"))
        y=int(raw_input("Input a number:"))
        z=x/y
    except ValueError,ev:
        print "That is no valid number.",ev
    except ZeroDivisionError,ez:
        print "divisor is zero:",ez
    except:
        print "Unexcepted error."
        raise
    else:                                 #当没有任何异常发生时,else语句的内容就被执行。else语句一定放在所有except语句后面。
        print "There is no error."
        print x,"/",y,"=",x/y
>>>
Input a number:4
Input a number:2
There is no error.
4 / 2 = 2
Input a number:4
Input a number:a
That is no valid number. invalid literal for int() with base 10: 'a'
>>>
Input a number:4
Input a number:0
divisor is zero: integer division or modulo by zero
Input a number:
6.类的定义可以放在程序的任何地方,通常是放在程序开始部分,import语句之后。
  可用点操作符为对象添加成员。
>>> class point:
    pass

>>> blank=point()
>>> blank.x=3.0
>>> blank.y=4.0
>>> print blank
<__main__.point instance at 0x00CD1EB8>                    #显示blank是点类point的一个实例,它被定义在_main_中。
>>> print blank.x
3.0
>>> print blank.y
4.0
>>>
>>> type(blank)
<type 'instance'>
>>> type(point)
<type 'classobj'>
>>> def printpoint(p):
    print '('+str(p.x)+','+str(p.y)+')'

   
>>> printpoint(blank)
(3.0,4.0)
>>>
7.copy模块中的copy方法(另外注意深拷贝deepcopy()的作用)
>>> p1=point()
>>> p1.x=2.0
>>> p1.y=4.0
>>> p2=p1
>>> print p1,p2
<__main__.point instance at 0x00CD1EB8> <__main__.point instance at 0x00CD1EB8>
>>> p2=copy.copy(p1)
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    p2=copy.copy(p1)
NameError: name 'copy' is not defined
>>> import copy
>>> p2=copy.copy(p1)
>>> print p1,p2
<__main__.point instance at 0x00CD1EB8> <__main__.point instance at 0x011A1D78>
8.可变参数的函数的定义(有的参数之所以可以省略,是因为函数中已经给出了缺省的参数)
>>> def total(head,tail,step):
    temp=0
    while head<tail:
        temp=temp+head
        head=head+step
    return temp

>>> total(1,10,1)
45
>>> def total(head,tail,step=1):
    temp=0
    while head<tail:
        temp=temp+head
        head=head+step
    return temp

>>> total(1,10)
45
>>> total(1,10,2)
25
>>>
注:缺省参数的定义要符合以下规则:缺省参数全部位于参数表的后部,而且缺省参数之间不能再有非缺省参数。
9.类的构造函数:
# 构造函数
class Time():
    def __init__(self,hours=0,minutes=0,seconds=0):
        self.hours=hours
        self.minutes=minutes
        self.seconds=seconds
    def printTime(self):
        print str(self.hours)+":"+/
              str(self.minutes)+":"+/
              str(self.seconds)

now=Time()
now.printTime()

nowTime=Time(20,16,18)
nowTime.printTime()
10.操作符重定义
class RMB:
    def __init__(self,sum=0.0):
        self.sum=sum

    def __str__(self):
        return str(self.sum)
    def __add__(self,other):
        return RMB(self.sum+other.sum)
    def __sub__(self,other):
        return RMB(self.sum-other.sum)

a=RMB(2000)
b=RMB(234.987)
print a+b,a.__add__(b)
print a-b,a.__sub__(b)
>>>
2234.987 2234.987
1765.013 1765.013
与乘法相关的方法有两个:一个是__mul__,另一个是__rmul__,可以在类中定义其中的一个,也可以两个都定义。
如果乘法操作符“*”的左右操作数都是用户定义的数据类型,那么调用__mul__,若左边的操作数是原始数据类型,而右边是用户定义数据类型,则调用__rmul__
class Line:
    def __init__(self,length=0.0):
        self.length=length

    def __str__(self):
        return str(self.length)
    def __mul__(self,other):
        return Rect(self.length,other.length)
    def __rmul__(self,other):
        return Line(self.length*other)

class Rect:
    def __init__(self,width=0.0,length=0.0):
        self.width=width
        self.length=length

    def __str__(self):
        return '('+str(self.length)+','+str(self.width)+')'
    def area(self):
        return self.width*self.length

aline=Line(5.87)
bline=2.9*Line(8.34)                              #必须严格把基本数据类型放在左边,否则会出错
print 'aline=',aline,'bline=',bline

rect=aline*bline
print rect
print rect.area()
>>>
aline= 5.87 bline= 24.186
(24.186,5.87)
141.97182
11.继承:继承提供了在已存在类的基础上创建新类的方法。继承的子类拥有被继承的父类的所有方法,在此基础上,子类还可以添加自己的专有方法
假设已经定义了一个父类BaseClass,那么子类的定义方式如下:
 class DerivedClass(BaseClass):
       ......
有时,子类中的方法可以直接调用父类中的方法。
12.私有方法或者属性只能被内部方法调用。在Python中,类的私有方法和私有属性,不能够从类的外面调用。类的方法和属性是私有还是公有,可以从它的名字判断。如果名字是以两个下划线开始,但并不是以两个下划线结束,则是私有的,其余的都是公有的。
import math
class point:
    def __init__(self,x=0,y=0):
        self.x=x
        self.y=y
    def __str__(self):
        return '('+str(self.x)+','+str(self.y)+')'

class Line:
    def __init__(self,p1=point(),p2=point()):
        self.__p1=p1
        self.__p2=p2
    def __str__(self):
        return str(self.__p1)+str(self.__p2)
    def __distance(self):
        tx=math.pow(self.__p1.x,2)+math.pow(self.__p2.x,2)
        ty=math.pow(self.__p1.y,2)+math.pow(self.__p2.y,2)
        return math.sqrt(tx+ty)
    def length(self):
        print self.__distance()
p1=point(2,3)
p2=point(3,4)
L1=Line(p1,p2)
print L1.__str__()
#L1.__distance()
L1.length()
>>>
(2,3)(3,4)
6.16441400297

抱歉!评论已关闭.