Python 基础语法(三)

来源:互联网 发布:java堆内存与栈内存 编辑:程序博客网 时间:2024/05/16 01:35

七、面向对象编程

  python支持面向对象编程;类和对象是面向对象编程的两个主要方面,类创建一个新的类型,对象是这个类的实例。

  对象可以使用普通的属于对象的变量存储数据,属于对象或类的变量被称为域;对象也可以使用属于类的函数,这样的函数称为类的方法;域和方法可以合称为类的属性。

  域有两种类型--属于实例的或属于类本身;它们分别被称为实例变量和类变量。

  类使用关键字class创建,类的域和方法被列在一个缩进块中。

  类的方法必须有一个额外的第一个参数,但是在调用时不为这个参数赋值,这个特殊变量指对象本身,按照惯例它的名称是self,类似C#中的this。

class Animal:    pass #empty block

  __init__方法  在类的一个对象被创建时调用该方法;相当于c++中的构造函数。

  __del__方法  在类的对象被销毁时调用该方法;相当于c++中的析构函数。在使用del删除一个对象时也就调用__del__方法。

  Python中所有的类成员(包括数据成员)都是public的;只有一个例外,如果使用的数据成员以双下划线为前缀,则为私有变量。

复制代码
class Person:    Count = 0    def __init__(self, name, age):        Person.Count += 1        self.name = name        self.__age = agep = Person("peter", 25)p1 = Person("john", 20)print Person.Count #2print p.name #peterprint p.__age #AttributeError: Person instance has no attribute '__age'
复制代码

  继承:为了使用继承,基类的名称作为一个元组跟在类名称的后面;python支持多重继承。下面是一个关于继承的例子:

复制代码
 1 class SchoolMember: 2     '''Represent any school member.''' 3     def __init__(self, name, age): 4         self.name = name 5         self.age = age 6         print "Initializing a school member." 7      8     def tell(self): 9         '''Tell my details'''10         print "Name: %s, Age: %s, " % (self.name, self.age),11 12 class Teacher(SchoolMember):13     '''Represent a teacher.'''14     def __init__(self, name, age, salary):15         SchoolMember.__init__(self, name, age)16         self.salary = salary17         print "Initializing a teacher"18 19     def tell(self):20         SchoolMember.tell(self)21         print "Salary: %d" % self.salary22 23 class Student(SchoolMember):24     '''Represent a student.'''25     def __init__(self, name, age, marks):26         SchoolMember.__init__(self, name, age)27         self.marks = marks28         print "Initializing a student"29 30     def tell(self):31         SchoolMember.tell(self)32         print "Marks: %d" % self.marks33 34 print SchoolMember.__doc__35 print Teacher.__doc__36 print Student.__doc__37 38 t = Teacher("Mr. Li", 30, 9000)39 s = Student("Peter", 25, 90)40 41 members = [t, s]42 43 for m in members:44     m.tell()
复制代码

  程序输出如下:

复制代码
Represent any school member.Represent a teacher.Represent a student.Initializing a school member.Initializing a teacherInitializing a school member.Initializing a studentName: Mr. Li, Age: 30,  Salary: 9000Name: Peter, Age: 25,  Marks: 90
复制代码

八、输入/输出

  程序与用户的交互需要使用输入/输出,主要包括控制台和文件;对于控制台可以使用raw_input和print,也可使用str类。raw_input(xxx)输入xxx然后读取用户的输入并返回。

  1. 文件输入/输出

    可以使用file类打开一个文件,使用file的read、readline和write来恰当的读写文件。对文件读写能力取决于打开文件时使用的模式,常用模式

  有读模式("r")、写模式("w")、追加模式("a"),文件操作之后需要调用close方法来关闭文件。

复制代码
 1 test = '''\ 2 This is a program about file I/O. 3  4 Author: Peter Zhange 5 Date: 2011/12/25 6 ''' 7  8 f = file("test.txt", "w") # open for writing, the file will be created if the file doesn't exist 9 f.write(test) # write text to file10 f.close() # close the file11 12 f = file("test.txt") # if no mode is specified, the default mode is readonly.13 14 while True:15     line = f.readline()16     if len(line) == 0:  # zero length indicates the EOF of the file17         break18     print line,19 20 f.close()
复制代码

  2. 存储器

    python提供一个标准的模块,成为pickle,使用它可以在一个文件中存储任何python对象,之后可以完整的取出来,这被称为持久地存储对象;还有另外一个模块成为cPickle,它的功能和pickle完全一样,只不过它是用c写的,要比pickle速度快(大约快1000倍)。

复制代码
import cPickledatafile = "data.data"namelist = ["peter", "john", "king"]f = file(datafile, "w")cPickle.dump(namelist, f)f.close()del namelistf = file(datafile)storednamelist = cPickle.load(f)print storednamelist#['peter', 'john', 'king']
复制代码

九、异常

  当程序中出现某些异常的状况时,异常就发生了。python中可以使用try ... except 处理。

复制代码
try:    print 1/0except ZeroDivisionError, e:    print eexcept:    print "error or exception occurred."#integer division or modulo by zero
复制代码

  可以让try ... except 关联上一个else,当没有异常时则执行else。

  我们可以定义自己的异常类,需要继承Error或Exception。

复制代码
class ShortInputException(Exception):    '''A user-defined exception class'''    def __init__(self, length, atleast):        Exception.__init__(self)        self.length = length        self.atleast = atleasttry:    s = raw_input("enter someting-->")    if len(s) < 3:        raise ShortInputException(len(s), 3)except EOFError:    print "why you input an EOF?"except ShortInputException, ex:    print "The lenght of input is %d, was expecting at the least %d" % (ex.length, ex.atleast)else:    print "no exception"#The lenght of input is 1, was expecting at the least 3
复制代码

  try...finally

复制代码
try:    f = file("test.txt")    while True:        line = f.readline()        if len(line) == 0:            break        time.sleep(2)        print line,finally:    f.close()    print "Cleaning up..."
0 0
原创粉丝点击