2007-02-01
Python学习笔记1--ICarnegieInfo
class ICarnegieInfo:
#single pattern by inner class
class __single:
def __init__(self):
ICarnegieInfo.address = "nwpu"
ICarnegieInfo.email = "tinylee@mail.com"
ICarnegieInfo.instance = "instance"
ICarnegieInfo.name = "tinylee"
ICarnegieInfo.telephone = "87654321"
ICarnegieInfo.url = "www.orchidy.com "
instance = None
def __init__(self):
if not ICarnegieInfo.instance:
ICarnegieInfo.instance = ICarnegieInfo.__single()
else:
return ICarnegieInfo.instance
def getAddress(self):
return self.address
def getEmail(self):
return self.email
def getInstance(self):
return self.name
def getTelephone(self):
return self.telephone
def getUrl(self):
return self.url
class ICarnegieApp:
def do(self):
handle = ICarnegieInfo()
while True:
try:
str = int(raw_input('\n0 Exit\n'
'1 Address\n'
'2 Email\n'
'3 Instance\n'
'4 Telephone\n'
'5 Url\n'
'Input your Choice>'));
except ValueError:
print "You should input a Integer."
continue
if str < 0 or str > 5:
print "Invalid input"
continue
elif str == 0:
break
elif str == 1:
ret = handle.getAddress()
elif str == 2:
ret = handle.getEmail()
elif str == 3:
ret = handle.getInstance()
elif str == 4:
ret = handle.getTelephone()
elif str == 5:
ret = handle.getUrl()
print ret
#main
app = ICarnegieApp()
app.do()
这个练习的目的:使用基本的循环和控制语句,使用单件模式,使用简单的异常处理。
需要注意的地方:
1。类名.属性名,表示该属性是类属性。所以在__single类中访问instance,需要加上ICarnegieInfo
2。方法定义的时候,如果有返回值,需要加上return语句,否则返回None,这个和java相同,和ruby不同。
3。从键盘中读取内容的方法:raw_input(''),但是会保留最后的回车。
从控制台输出的方法:print
4。捕捉类型转换的异常是ValueError。
5。相邻的字符串连接的时候,可以不用+