#单例模型(重要)
class Person (object):
__instance = None
is_first = True
def __new__(cls, *args, **kwargs):
#如果类属性__instance的值为None
#创建一个对象,并赋值为这个对象的引用,保证下次调用这个方法时
#能够知道之前已经创建过对象了,这样就保证了只有一个对象
if not cls.__instance: #保存第一次创建对象
cls.__instance = object.__new__(cls)
return object.__new__(cls) #返回第一次创建的对象
def __init__(self, name, age):
if Person.is__first:
self.name = name
self.age = age
xm = Person("小明",18)
xh = Person("小红",16)
print(id(xm))
print(id(xh)) #小明和小红的id相同 返回的ID都唯一
a = 6.99
b = 3.2
c = a * b
print(c) #输出 22.368000000000000002
from decimal import Decimal #精确输出
from decimal import getcontext #设置精度
print(Decimal("6.99")*Decimal("3.2))
getcontext().prec = 2 #精度为2
print(Decimal("6.99")*Decimal("3.2))
def t1():
l = []
for i in range(1000):
l.append(i)
def t2():
l = []
for i in range(1000):
l = l + [i] #使用 += 更快
def t3():
l = [i for i in range(1000)]
def t4():
l = list(range(1000))
from timeit import Timer #可以测试代码运行时间
time1 = Timer("t1()","from __main__ import t1") #第一个参数为执行的函数 第二个为从入口导入函数
print(time1.timeit(number = 10000)) #输出执行10000次time1函数所耗的时间 默认为一百万次
time2 = Timer("t2()","from __main__ import t2")
print(time2.timeit(number = 10000))
time3 = Timer("t3()","from __main__ import t3")
print(time3.timeit(number = 10000))
time4 = Timer("t4()","from __main__ import t4") #用时最短
print(time4.timeit(number = 10000))
#if __name__ == '__main__': #入口函数
import time
start_time = time.time()
#假装此处有代码
end_time =time.time()
print(end_time - start_time) #可以用来计算所耗时间
冒泡排序
def bubble_sort(alist):
n = len(alist)
for i in range(n-1)
print("*")
count = 0
for j in range(n-1-i):
if alist[j] >= alist[j+1]:
alist[j],alist[j+1] = alist[j+1],alist[j]
count+=1
if count == 0:
break
if___name___=='__main__':
alist =[12,323,234,55454,32,323]
bubble_sort(alist)
print(alist)
抛出异常
try: # 尝试
open("adsaadx.txt")
except FileNotFoundError as a: # FileNotFoundError 为异常类型 发生异常后保存异常信息并打印
print("错误",a)
else: #未捕获到异常执行
print("else")
finally: #无论是否捕获都执行
print("finally")
自定义异常类
class AgeError(Exception):
def __init__(self, age):
self.age = age
def __str__(self):
return"1-15之间,age = %d" % self.age
class person(object):
def __init__(self,name,age):
if age > 0 and age <= 15:
self.name = name
self.age = age
else: # 如果年龄不在0-15之间提示异常
# print("您输入错误了")
raise AgeError(age) #抛出异常
xm = Person("小明",1123)
class Test(object):
def __init__(self,switch):
self.swith = switch #顶一个开关
def num(self,a,b):
try:
return a/b
except Exception as result:
if self.switch: # 如果switch 为真则打印
print(result)
else: # 为假则抛出异常
raise
a = Test(True)
a.num(11,0)