Python异常处理,类的私有属性
异常处理:格式:tryxxxxexcept 错误类型,变量名(可省):print "XXXXXXXXXXXX",变量名(可省)例:#!/bin/env pythonimport timetry:name=['a','b','c']name[3]##第一个错,对应IndexErrorinfo_dic={}
·
异常处理:
格式:
try
xxxx
except 错误类型,变量名(可省):
print "XXXXXXXXXXXX",变量名(可省)
例:
#!/bin/env python
import time
try:
name=['a','b','c']
name[3] ##第一个错,对应IndexError
info_dic={}
info_dic['alex'] ##第二个错,对应IndentationError
time.sleep(10) ##ctrl+c,对应KeyboardInterrupt
except IndexError:
print 'You list are wrong!'
except IndentationError:
print 'No valid key'
except KeyboardInterrupt:
print 'sfdssdf'
还可以手动触发异常:
try:
name=raw_input()
if len(name)==0:
raise IndexError ##当name输入为空时即报错为IndexError类型。
except IndexError:
print 'You list are wrong!'
#!/bin/env python
class AlexException(Exception):
def __init__(self,err):
print 'The name you input is not correct!',err
try:
name=raw_input('Nmae:').split()
if name[0] != 'alex':
raise AlexException(name)
except AlexException:
print "No valid name ..."
类的私有属性:
在类方法前加__即是私有
#!/bin/env python
#!coding=utf-8
class person(object):
def __init__(self,name,age):
self.Name=name
self.Age=age
print 'haha:%s,%s' %(name,age)
def sayHi(self):
print 'Hi,my name is %s,age is %s' %(self.Name,self.Age)
#self.__talk() ##只可在函数内部调用
def __talk(self):
print 'I Speak English'
#def __del__(self):
# print 'I got killed just now ... bye ... %s'%self.Name
p=person('Alex',29)
p._person__talk() ##函数外部调用需要有该特定的格式,但不建议如此调用。
更多推荐
所有评论(0)