找回密码
 会员注册
查看: 43|回复: 0

100个python的基本语法知识下

[复制链接]

2万

主题

0

回帖

6万

积分

超级版主

积分
64454
发表于 2024-9-2 20:00:36 | 显示全部楼层 |阅读模式
50.压缩文件:importzipfilewithzipfile.ZipFile("file.zip","r")aszip_ref:zip_ref.extractall("extracted")123451.数据库操作:importsqlite3conn=sqlite3.connect("my_database.db")cursor=conn.cursor()cursor.execute("CREATETABLEIFNOTEXISTSusers(idINTEGERPRIMARYKEY,nameTEXT)")conn.commit()conn.close()123456752.网络请求:importrequestsresponse=requests.get("https://www.example.com")12353.多线程:importthreadingdefmy_thread():print("Threadrunning")thread=threading.Thread(target=my_thread)thread.start()thread.join()1234567854.多进程:importmultiprocessingdefmy_process():print("Processrunning")process=multiprocessing.Process(target=my_process)process.start()process.join()1234567855.进程池:frommultiprocessingimportPooldefmy_function(x):returnx*xwithPool(5)asp:print(p.map(my_function,[1,2,3]))123456756.队列:fromqueueimportQueueq=Queue()q.put(1)q.put(2)q.get()12345657.协程:importasyncioasyncdefmy_coroutine():awaitasyncio.sleep(1)print("Coroutinerunning")asyncio.run(my_coroutine())123456758.异步IO:importaiohttpimportasyncioasyncdeffetch(url):asyncwithaiohttp.ClientSession()assession:asyncwithsession.get(url)asresponse:returnawaitresponse.text()loop=asyncio.get_event_loop()loop.run_until_complete(fetch("https://www.example.com"))1234567891059.信号处理:importsignaldefhandler(signum,frame):print("Signalhandlercalledwithsignal",signum)signal.signal(signal.SIGINT,handler)12345660.装饰器的实现:defmy_decorator(func):defwrapper(*args,**kwargs):print("Beforefunctioncall")result=func(*args,**kwargs)print("Afterfunctioncall")returnresultreturnwrapper123456761.基于类的装饰器:classMyDecorator:def__init__(self,func):self.func=funcdef__call__(self,*args,**kwargs):print("Beforefunctioncall")result=self.func(*args,**kwargs)print("Afterfunctioncall")returnresult12345678962.模块和包的导入:frommy_packageimportmy_module163.相对导入:from.my_moduleimportmy_function164.集合操作:set1={1,2,3}set2={2,3,4}set1&set2#交集set1|set2#并集set1-set2#差集1234565.集合方法:my_set.add(5)my_set.remove(5)1266.字典方法:my_dict.keys()my_dict.values()my_dict.items()12367.对象方法:classMyClass:defmethod(self):passobj=MyClass()obj.method()12345668.类方法:classMyClassclassmethoddefmethod(cls):pass123469.静态方法:classMyClassstaticmethoddefmethod():pass123470.上下文管理器的实现:classMyContextManager:def__enter__(self):passdef__exit__(self,exc_type,exc_val,exc_tb):passwithMyContextManager():pass12345678971.元类:classMyMeta(type):def__new__(cls,name,bases,dct):returnsuper().__new__(cls,name,bases,dct)12372.装饰器链:@decorator1@decorator2defmy_function():pass123473.属性的getter和setter:classMyClass:def__init__(self,value):self._value=value@propertydefvalue(self):returnself._value@value.setterdefvalue(self,new_value):self._value=new_value123456789101174.文件操作:withopen("file.txt","r")asfile:content=file.read()1275.with语句:withopen("file.txt","r")asfile:content=file.read()1276.yield语句:defmy_generator():yield1yield2yield3123477.生成器表达式:gen=(x**2forxinrange(10))178.列表方法:my_list.append(5)my_list.remove(5)1279.元组解包:a,b,c=(1,2,3)180.字典解包:defmy_function(a,b,c):passmy_dict={'a':1,'b':2,'c':3}my_function(**my_dict)1234581.循环中断:foriinrange(10):ifi==5:break12382.循环跳过:foriinrange(10):ifi==5:continue12383.异步编程:importasyncioasyncdefmy_coroutine():awaitasyncio.sleep(1)asyncio.run(my_coroutine())12345684.类型检查:isinstance(5,int)185.序列化和反序列化:importpickledata={"name":"John","age":30}withopen("data.pkl","wb")asfile:pickle.dump(data,file)withopen("data.pkl","rb")asfile:data=pickle.load(file)1234567886.文件读取模式:withopen("file.txt","r")asfile:content=file.read()1287.文件写入模式:withopen("file.txt","w")asfile:file.write("Hello,World!")1288.上下文管理器:withopen("file.txt","r")asfile:content=file.read()1289.命令行参数解析:importargparseparser=argparse.ArgumentParser(description="Myprogram")parser.add_argument("name",type=str,help="Yourname")args=parser.parse_args()1234590.模块导入:importmy_module191.包导入:frommy_packageimportmy_module192.包的相对导入:from.my_moduleimportmy_function193.动态属性:classMyClass:def__init__(self):self.dynamic_attr="Iamdynamic"12394.动态方法:defdynamic_method(self):return"Iamdynamic"MyClass.dynamic_method=dynamic_method123495.类的单例模式:classSingleton:_instance=None1296.类的工厂模式:classFactory:defcreate(self,type):iftype=="A":returnA()eliftype=="B":returnB()12345697.依赖注入:classService:def__init__(self,dependency):self.dependency=dependency12398.抽象类:fromabcimportABC,abstractmethodclassAbstractClass(ABC)abstractmethoddefmy_method(self):pass12345699.接口:fromabcimportABC,abstractmethodclassInterface(ABC)abstractmethoddefmethod(self):pass12345这些知识点涵盖了Python编程的基本语法和常用功能。希望对你有帮助!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 会员注册

本版积分规则

QQ|手机版|心飞设计-版权所有:微度网络信息技术服务中心 ( 鲁ICP备17032091号-12 )|网站地图

GMT+8, 2024-12-27 00:41 , Processed in 1.472471 second(s), 25 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表