声明:本文整理于虫师的博客,记载一些知识点。
类
创建类
创建自己的类,先来看一个简单的类:
_metaclass_ = type #确定新式类
class Person:
def setName(self,name):
self.name = name
def getName(self):
return self,name
def greet(self):
print "Hello, world! I'm %s" %self.name
注意:新式类的语法中,需要在模块或者脚本开始的地方放置赋值语句metaclass = type 。
创建了一个Person的类,这个类包含了三个方法定义,只是那个self看起有点奇怪,它是对于对象自身的引用。
让我们创建实例看看:
>>> huhu = Person()
>>> huhu.setName('hu zhiheng')
>>> huhu.greet()
Hello, world! I'm hu zhiheng
应该能说明self的用处了,在调用huhu的setName 和 greet 函数时,huhu自动将自己作为第一个参数传入函数中—-因此形象地命名为self。每个人可能都会有自己的叫法,但是因为它总是对象自身,所以习惯上总是叫做self 。
构造方法
构造方法与其的方法不一样,当一个对象被创建会立即调用构造方法。创建一个python的构造方法很简答,只要把init方法,从简单的init方法,转换成魔法版本的init方法就可以了。
class FooBar:
def __init__(self):
self.somevar = 42
>>> f =FooBar()
>>> f.somevar
超类
子类可以扩展超类的定义。将其他类名写在class语句后的圆括号内可以指定超类:
class Filter:
def init(self):
self.blocked = []
def filter(self , sequence):
return [x for x in sequence if x not in self.blocked]
class SPAMFilter(Filter): #SPAMFilter是Filter的子类
def init(self): #重写Filter类中的init方法
self.blocked = ['SPAM']
Filter 是个用于过滤序列的通用类,事实上它不能过滤任何东西:
>>> f = Filter()
>>> f.init()
>>> f.filter([1,2,3])
[1, 2, 3]
Filter 类的用户在于它可以用作其他类的基类(超类,“java中叫父类”),比如SPAMFilter类,可以将序列中的“SPAM”过滤出来。
>>> s = SPAMFilter()
>>> s.init()
>>> s.filter(['SPAM','SPAMD','SPAM','HELLO','WORLD','SPAM'])
['SPAMD', 'HELLO', 'WORLD']
调查继承
如果想要查看一个类是否是另一个的子类。可以使用内建的issubclass函数:
>>> issubclass(SPAMFilter, Filter)
True
>>> issubclass(Filter,SPAMFilter)
False
属性
访问器是一个简单的方法,它能够使用getHeight 、setHeight 之样的名字来得到或者重绑定一些特性。如果在访问给定的特性时必须要采取一些行动,那么像这样的封装状态变量就很重要。如下:
class Rectangle:
def __init__(self):
self.width = 0
self.height = 0
def setSize(self,size):
self.width , self.height = size
def getSize(self):
return self.width , self.height
>>> r = Rectangle()
>>> r.width = 10
>>> r.height = 5
>>> r.getSize()
(10, 5)
>>> r.setSize((150,100))
>>> r.width
在上面的例子中,getSize和setSize方法一个名为size的假想特性的访问器方法,size是由width 和height构成的元组。
property 函数
property函数的使用很简单,如果已经编写了一个像上节的Rectangle 那样的类,那么只要增加一行代码:
__metaclass__ = type
class Rectangle:
def __int__(self):
self.width = 0
self.height = 0
def setSize(self,size):
self.width, self.height = size
def getSize(self):
return self.width ,self.height
size = property(getSize ,setSize)
>>> r = Rectangle()
>>> r.width = 10
>>> r.height = 5
>>> r.size
(10, 5)
>>> r.size = 150,100
>>> r.width
在这个新版的Retangle 中,property 函数创建了一个属性,其中访问器函数被用作参数(先取值,然后是赋值),这个属性命为size 。这样一来就不再需要担心是怎么实现的了,可以用同样的方式处理width、height 和size。
python异常
python用异常对象(exception object)来表示异常情况。遇到错误后,会引发异常。如果异常对象并未被处理或捕捉,程序就会用所谓的 回溯(Traceback, 一种错误信息)终止执行:
>>> 1/0
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
1/0
ZeroDivisionError: integer division or modulo by zero
raise 语句
为了引发异常,可以使用一个类(Exception的子类)或者实例参数数调用raise 语句。下面的例子使用内建的Exception异常类:
>>> raise Exception #引发一个没有任何错误信息的普通异常
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
raise Exception
Exception
>>> raise Exception('hyperdrive overload') # 添加了一些异常错误信息
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
raise Exception('hyperdrive overload')
Exception: hyperdrive overload
自定义异常
尽管内建的异常类已经包括了大部分的情况,而且对于很多要求都已经足够了,但有些时候还是需要创建自己的异常类。
和常见其它类一样—-只是要确保从Exception类继承,不管直接继承还是间接继承。像下面这样:
>>> class someCustomExcetion(Exception):pass
捕捉异常
我们可以使用 try/except 来实现异常的捕捉处理。
假设创建了一个让用户输入两个数,然后进行相除的程序:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
#运行并且输入
Enter the first number: 10
Enter the second number: 0
Traceback (most recent call last):
File "I:/Python27/yichang", line 3, in <module>
print x/y
ZeroDivisionError: integer division or modulo by zero
为了捕捉异常并做出一些错误处理,可以这样写:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except ZeroDivisionError:
print "输入的数字不能为0!"
#再来运行
>>>
Enter the first number: 10
Enter the second number: 0
输入的数字不能为0!
假如,我们在调试的时候引发异常会好些,如果在与用户的进行交互的过程中又是不希望用户看到异常信息的。那如何开启/关闭 “屏蔽”机制?
class MuffledCalulator:
muffled = False #这里默认关闭屏蔽
def calc(self,expr):
try:
return eval(expr)
except ZeroDivisionError:
if self.muffled:
print 'Divsion by zero is illagal'
else:
raise
#运行程序:
>>> calculator = MuffledCalulator()
>>> calculator.calc('10/2')
>>> calculator.clac('10/0')
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
calculator.clac('10/0')
AttributeError: MuffledCalulator instance has no attribute 'clac' #异常信息被输出了
>>> calculator.muffled = True #现在打开屏蔽
>>> calculator.calc('10/0')
Divsion by zero is illagal
多个except 子句
如果运行上面的(输入两个数,求除法)程序,输入下面的内容,就会产生另外一个异常:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except ZeroDivisionError:
print "输入的数字不能为0!"
#运行输入:
>>>
Enter the first number: 10
Enter the second number: 'hello.word' #输入非数字
Traceback (most recent call last):
File "I:\Python27\yichang", line 4, in <module>
print x/y
TypeError: unsupported operand type(s) for /: 'int' and 'str' #又报出了别的异常信息
好吧!我们可以再加个异常的处理来处理这种情况:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except ZeroDivisionError:
print "输入的数字不能为0!"
except TypeError: # 对字符的异常处理
print "请输入数字!"
#再来运行:
>>>
Enter the first number: 10
Enter the second number: 'hello,word'
请输入数字!
一个块捕捉多个异常
我们当然也可以用一个块来捕捉多个异常:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except (ZeroDivisionError,TypeError,NameError):
print "你的数字不对!"
捕捉全部异常
就算程序处理了好几种异常,比如上面的程序,运行之后,假如我输入了下面的内容呢
>>>
Enter the first number: 10
Enter the second number: #不输入任何内容,回车
Traceback (most recent call last):
File "I:\Python27\yichang", line 3, in <module>
y = input('Enter the second number: ')
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
晕死~! 怎么办呢?总有被我们不小心忽略处理的情况,如果真想用一段代码捕捉所有异常,那么可在except子句中忽略所有的异常类:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except:
print '有错误发生了!'
#再来输入一些内容看看
>>>
Enter the first number: 'hello' * )0
有错误发生了!
用户不小心输入了错误的信息,能不能再给次机会输入?我们可以加个循环,保你输对时才结束:
while True:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
value = x/y
print 'x/y is',value
break
except:
print '无效输入,再来一次!'
#运行
>>>
Enter the first number: 10
Enter the second number:
无效输入,再来一次!
Enter the first number: 10
Enter the second number: 'hello'
无效输入,再来一次!
Enter the first number: 10
Enter the second number: 2
x/y is 5