您的位置:首页 > 编程语言 > Python开发

python基础语法(3)

2015-09-28 16:55 573 查看
七、面向对象编程

  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 = age

p = Person("peter", 25)
p1 = Person("john", 20)

print Person.Count #2
print p.name #peter
print 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 = salary
17         print "Initializing a teacher"
18
19     def tell(self):
20         SchoolMember.tell(self)
21         print "Salary: %d" % self.salary
22
23 class Student(SchoolMember):
24     '''Represent a student.'''
25     def __init__(self, name, age, marks):
26         SchoolMember.__init__(self, name, age)
27         self.marks = marks
28         print "Initializing a student"
29
30     def tell(self):
31         SchoolMember.tell(self)
32         print "Marks: %d" % self.marks
33
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 teacher
Initializing a school member.
Initializing a student
Name: Mr. Li, Age: 30,  Salary: 9000
Name: 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 file
10 f.close() # close the file
11
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 file
17         break
18     print line,
19
20 f.close()


  2. 存储器

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

import cPickle

datafile = "data.data"

namelist = ["peter", "john", "king"]

f = file(datafile, "w")
cPickle.dump(namelist, f)
f.close()

del namelist

f = file(datafile)
storednamelist = cPickle.load(f)

print storednamelist
#['peter', 'john', 'king']


九、异常

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

try:
print 1/0
except ZeroDivisionError, e:
print e
except:
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 = atleast

try:
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..."
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: