python笔记源代码


"""
import copy
#浅复制1
l9=[1,2,3,4,5,6]
l=[]
l.append(l9)
print(l9,id(l9))
print(l,id(l))
#浅复制2
l5=[1,2,3,4,5]
l6=l5.copy()
print(l5,id(l5))
print(l6,id(l6))
#浅复制3
l7=[1,2,3,4,5]
l8=copy.copy(l7)
print(l7,id(l7))
print(l8,id(l8))
#深复制
l1=[[1,2],2,3,4]
l2=copy.deepcopy(l1)
print(l1,id(l1))
print(l2,id(l2))

l9=[1,2,3,4,5,6]
l=[]
l.append(l9)
print(l9,id(l9))
print(l,id(l))
"""
"""
j1={1,2,3,4,5}
j2={3,4,5,6,7}
print(j1&j2)
#四种数值类型
a=6
b=3.1415
c=True
d=2+5j
#序列类型
e="happy"
f=['h','a','p','p','y']
g=('h','a','p','p','y')
#散列类型
h={'1':'h','2':'a','3':'a','4':'p','5':'y'}
i={'h','a','p','p','y'}
#可变的 :列表 字典 集合
#不可变的:数字 字符串 元组
#字典的方法
#增
d1={'name':'a','age':18,'hobby':'music'}
d2=d1.copy()
print(d2)
d3=dict.fromkeys([1,2,3],1)
print(d3)
print(d1.setdefault('gender','man'))
print(d1)
#查
print(d1.get('name'))
print(list(d1.keys()))
print(list(d1.values()))
print(d1.items())
#改
dd={'tj':'这是添加的内容'}
d1.update(dd)
print(d1)
#删
d1.pop('hobby')
print(d1)
d1.popitem()
print(d1)
d1.clear()
print(d1)
"""
"""
for i in range(1,10):
	for j in range(1,i+1):
		print("%d*%d=%d " % (i,j,i*j),end="")
	print("\n")
	i+=1
"""
"""
#临时排序
def myorder1(c1,li1):
    return sorted(li1,reverse=c1)
print(myorder1(True,[2,2,3,4,1,6,7]))

#永久排序
def myorder2(c1,li2):
	li2.sort(reverse=c1)
	return li2
print(myorder2(False,[2,6,34,78,12,2,1]))

#课堂代码练习
def printword():
	print('这里写代码')
printword()

def a_add_b(sum1,sum2):
	sum3=sum1+sum2
	return '计算结果:sum3=%d'%sum3
print(a_add_b(1,3))

def sum(sum1,sum2,sum3=100,*args,**kargs):
	sum4=sum1+sum2
	print('计算结果为:',end="\t")
	print(sum4)
	print(args)
	print(type(kargs))
print(sum(1,2,1,2,3,4,5,6,))
#函数enumerate
myli=['a','b','c']
print(list(enumerate(myli)))
print(dict(enumerate(myli)))
#函数exec eval
mystr='''print("this a amazing!")
print("you are low")'''
mystr1='''print("this a amazing!")'''
print(eval(mystr1))
print(exec(mystr))
#函数filter
def fn1(c1):
	if c1>10:
		return True
	else :
		return False
print(list(filter(fn1,[1,2,5,6,3,67,45,10])))
#函数map 对可迭代对象每个元素进行操作
def fn2(c1):
	return c1+1
print(list(map(fn2,[1,2,3,4,5,6,7,8,9,10])))
#可迭代对象的匹配 对可迭代对象每个元素进行过滤
dli1=['name','age','hobby']
dli2=['xiaohua','12','music']
print(dict(zip(dli1,dli2)))
myinput=input("请输入:")
"""
"""
#排序函数
a=[1,4,2,7,67,45,22]
a.sort()
print(a)
a.sort(reverse=True)
print(a)
b=[1,2,12,3,45]
print(sorted(b,reverse=False))
print(sorted(b,reverse=True))
b.reverse()
print(b)
"""
"""
#递归求和
def gs(c1):
	if c1==1:
		return 1
	else:
		return c1+gs(c1-1)
print(gs(100))
#交换元组与字典的值
def change(c_dict,c_tuple):
	new_tuple=tuple(c_dict.values())
	new_keys=tuple(c_dict.keys())
	new_dict=dict(zip(new_keys,c_tuple))
	return new_dict,new_tuple
result=change({'a':'1','b':'2','c':'3'},(4,5,6))
print(result[0])
print(result[1])
"""
"""
#类的实例化
class Rectangle():
	def __init__(self,length,width):
		self.length=length
		self.width=width
	def getarea(self):
		return self.length*self.width
a=Rectangle(20,30)
print(a.getarea())

class Animal():
	def __init__(self,a_type,name,age,color):
		self.a_type=a_type
		self.name=name
		self.age=age
		self.color=color
	def p_appearance(self):
		print("动物:%s" % self.a_type)
		print("它的名字叫做%s" % self.name)
		print("今年%s岁了" % self.age)
		print("它的毛色是%s" % self.color)
		print('\n')
b=Animal('猫','豆豆',2,'白色')
b.p_appearance()
c=Animal('狗','小黄',3,'黄色')
c.p_appearance()

class Car():
	_value=1000000
	color='white'
	date='2018-5-6'
c1=Car()
c1.name='BWM'
print('车名:'+c1.name)
print('价值:'+str(c1._value))
print('外观:'+c1.color)
print('生产时间:'+c1.date)
"""
"""
# init重写
class Rectangle():
	def __init__(self,length,width):
		self.length=length
		self.width=width
	def getarea(self):
		return self.length*self.width
class Square(Rectangle):
	def __init__(self,side_length):
		super().__init__(side_length,side_length)
	def square_area(self):
		return self.getarea()
a=Square(12)
area=a.square_area()
print(area)
"""
"""
#类的析构
class Person(object):
	def __init__(self, name):
		self.name=name
	def get(self):
		print("%s获得一件装备"%self.name)
	def __del__(self):
		print("装备已回收")
a=Person("evil")
a.get()
#多继承
class Father(object):
	def __init__(self,hobby):
		self.hobby=hobby
	def data(self):
		print("爱好:%s" % (self.hobby))
	def run(self):
		print("跑的特快!")
	def dance(self):
		print("爱跳爵士舞!")
	_gender='man'
class Mother(object):
	def __init__(self,hobby):
		self.hobby=hobby
	def data(self):
		print("爱好:%s" % (self.hobby))
	def cook(self):
		print("做的饭很香!")
	def dance(self):
		print("爱跳芭蕾舞!")
class Son(Father,Mother):
	def play(self):
		print("特别爱玩游戏!")
a=Son("music")
a.run()
a.cook()
a.data()
a.dance()#如果存在一样的方法,则先继承左边
print(a._gender)
#调用父类方法
class Base:
	def display(self):
		print("this is base!")
class A(Base):
	def display(self):
		super().display()
		print("this is A!")
class B(Base):
	def display(self):
		super().display()
		print("this is B!")
class C(A,B):
	def display(self):
		super().display()
		print("this is C!")
a=A()
a.display()
b=B()
b.display()
c=C()
c.display()
print(C.__mro__)
"""
"""
#魔术方法
class Rectangle():
	def __init__(self,length,width):
		self.length=length
		self.width=width
	def __add__(self,other):
		add_length=self.length+other.length
		add_width=self.width+other.width
		return add_length,add_width
	def __sub__(self,other):
		sub_length=self.length-other.length
		sub_width=self.width-other.width
		return sub_length,sub_width
a=Rectangle(1,2)
b=Rectangle(1,2)
print(a+b)
print(a-b)
"""
"""
#__str__和__repr__ 打印信息的方法
class A():
	def __init__(self,name):
		self.name=name
	def __str__(self):
		return 'this is %s in str!' % self.name
	def __repr__(self):
		return 'this is %s in repr!' % self.name
a=A("class")
print(a.__str__())
print(a.__repr__())
"""
"""
#call方法
class A():
	def __init__(self,name):
		self.name=name
	def __call__(self):
		print("this is call!")
a=A("peter")
a()
"""
"""
#单例模式
class Earth:

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls,'instance'):
            cls.instance = super().__new__(cls)
        return cls.instance         # 必须返回父类的new方法
    def __init__(self,name):
        self.name = name
        print('%s这是init方法'%self.name)
a = Earth('寒沙')
b = Earth('清水')
print(id(a))
print(id(b))
"""
"""
#定制属性访问
class Flowers():
	color='red'
	def __init__(self,name,color):
		self.name=name
		self.color=color
	def exclaim(self):
		print("花名:%s" % self.name)
		print("颜色:%s" % self.color)
f=Flowers('玫瑰','红色')
f.exclaim()
print(hasattr(f,'color'))
print(getattr(f,'color'))
setattr(f,'meaning','浪漫')
print(getattr(f,'meaning'))
delattr(f,'meaning')
print(getattr(f,'meaning'))
"""
"""
#描述符
class Game():
	def __init__(self,name,press_time):
		self.name=name
		self.press_time=press_time
	def __get__(self,instance,owner):
		print("已引用!")
	def __set__(self,instance,value):
		print("已赋值!")
	def __delete__(self,instance):
		print("已删除!")
	def p_detail(self):
		print("%s" % self.name)
		print("%s" % self.press_time)
class Myclass():
	attr=Game('m','2008')
m=Myclass()
m.attr
m.attr=1
del m.attr
"""
"""
#装饰器
def aa(fn):
	def bb():
		print("验证中...")
		fn()
	return bb
def fn():
	print("登录中...")
@aa
def f1():
	print("登录中...")
f1()
@aa
def f2():
	print("登陆成功...")
f2()
#内置类方法装饰器
class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width
    def area(self):
        areas = self.length * self.width
        return areas
    @property  	# 就像访问属性一样和普通访问少了一个()
    def area(self):
        return self.width * self.length
    @staticmethod
    def func():
    	print("staticmethod")
    @classmethod
    def show(cls):
    	print(cls)
    	print("show function")
r=Rectangle(12,12)
print(r.area)
Rectangle.func()
r.show()
class Test():
	def __init__(self,func):
		self.func=func
	def __call__(self):
		print("类")
@Test
def myfun():
	print("这是一个测试函数")
myfun()
"""
"""
#测试函数运行时间
import time
def run_time(func):
	def new_fun(*args,**kwargs):
		t0=time.time()
		back=func(*args,**kwargs)
		print("函数运行时间:%f" % float(t0-time.time()))
		return back
	return new_fun
@run_time
def myfun():
	type("")

import time
def run_time(func):
	def wrapper():
		start_time=time.time()
		time.sleep(1)
		result=func()
		right_time=time.time()-start_time
		print("%s运行时间:" % func)
		print(float(right_time-1))
		return result
	return wrapper
@run_time
def myfunc1():
	type('123')
myfunc1()
@run_time
def myfunc2():
	isinstance('123',str)
myfunc2()
"""
"""
#文件复制
import os
def filecopy(f1_dress,f2_dress):
	with open(f1_dress,"r+")as f1,open(f2_dress,"w+")as f2:
		data=f1.read()
		f2.write(data)
		print("复制成功!")

#文件遍历
import os
def travel_dir(dress):
	dir_contents=os.listdir(dress)                         #获取目录下的内容
	dir_content="\n".join(dir_contents)                    #将列表形式内容转化为字符串
	print("目录:{} \n内容:\n{}\n".format(dress,dir_content))
	for i in dir_contents:                                 #遍历列表的内容
		try:
				new_dir=os.path.join(dress,i)              #拼接成绝对路径
				if os.path.isdir(new_dir):                 #选择是目录的绝对路径
					travel_dir(new_dir)                    #调用函数自身继续操作
		except PermissionError:continue                    #排除有权限异常的目录
travel_dir("c:\\")
"""
"""
a=lambda x:x*x
print(a(5))
def choice(a):
	if a>5:
		return 1
	else:
		return 0
li=[1,2,3,4,5,6,7]
new_li=map(lambda x:x*2+4,li)

a=filter(choice,li)

b=map(choice,li)
print(list(a))
print(list(b))
"""

猜你喜欢

转载自blog.csdn.net/qq_44647926/article/details/88536654
今日推荐