Python異常處理,類的私有屬性
阿新 • • 發佈:2019-02-17
異常處理:
格式:
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() ##函式外部呼叫需要有該特定的格式,但不建議如此呼叫。