只初始化一次对象
对象有a,b,如何让对象只初始化一次?
class Dog(object):
__instance = None
__init_flag = False
def __new__(cls,name):
if cls.__instance == None:
cls.__instance = object.__new__(cls)
else:
#return 上一次创建的对象的引用
return cls.__instance
def __init__(self, name):
if Dog.__init_flag == False:
self.name = name
Dog.__init_flag = True
a = Dog("旺财")
print(id(a))
print(a.name)
b = Dog("哮天犬")
print(id(b))
print(b.name)
异常处理
预案,出现异常,如何处理?
try:
open("xxx.txt")
print(num)
print("--------")
except (NameError,FileNotFoundError): #异常的名字(错误类型)多个需要元祖
print("如果捕获到异常后做的 处理...") #弥补的代码
except Exception as ret:
print("如果用了exception,意味着所有的except一定可以捕获到")
print(ret)#得到异常的名字
else:
print("没有隐藏才会执行的功能")
finally:
print("-----finally-----")#不管是否产生异常,最后都要执行这个
异常传递
抛出自定义异常
class ShortInputException(Exception):
'''自定义的异常类'''
def __init__(self, length, atleast):
#super().__init__()
self.length = length
self.atleast = atleast
def main():
try:
s = input("请输入-->")
if len(s)<3:
#raise引发一个你定义的异常
raise ShortInputException(len(s),3)
except ShortInputException as result:#这个变量被绑定到了错误的实例
print("ShortInputException:输入的长度是 %d,长度至少应是 %d"%(result.length,result.atleast))
else:
print("没有异常发生")
main()
异常处理中抛出异常
类似于小区雇了一个保安,在处理某个异常时退缩了,一个月1000的工资,不想玩命
class Test(object):
def __init__(self, switch):
self.switch = seitch
def calc(self, a,b):
try:
return a/b
except Exception as result:
if self.switch:
print("捕获开启,已经捕获到异常,信息如下:")
print(result)
else:
#重新跑出这个异常,此时就不会被这异常处理给捕获到,从而触发默认的异常处理
raise
a = Test(True)
a.calc(11,0)
print("------------华丽的分割线------------")
a.switch = False
a.calc(11,0)
if的各种真假判断
数字0表示假,非0表示真
if xxxx: 看结果是 真还是假
if xxx==0 看条件是否成立
模块
具有很多功能的集合,称py文件为模块
pip是管理管理python模块的工具
sudo pip3 install pygame
三种导入方式
#import sendmsg
#sendmsg.test1()
#senfmsg.test2()
#from sendmsg import test1,test2
from sendmsg import * #所有的函数都导入进去了
test1()
test2()
此外, imoport time as tt #给模块起小名
自我测试时可以用,老大main()导入时不能执行
def test1():
print("-----test1-----")
def test2():
print("-----test2-----")
if __name__ == "__main__":
test1()
test2()
__name__这个变量非常独特,自己调用时 显示是__main__字符串,别人导入你的函数,打印的是你模块的名字
在公司里,一般都是下边这种流程