百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术教程 > 正文

100个python的基本语法知识【下】

csdh11 2025-04-28 23:59 12 浏览

50. 压缩文件:

import zipfile


with zipfile.ZipFile("file.zip", "r") as zip_ref:
    zip_ref.extractall("extracted")

51. 数据库操作:

import sqlite3

conn = sqlite3.connect("my_database.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
conn.commit()
conn.close()

52. 网络请求:

import requests
response = requests.get("https://www.example.com")

53. 多线程:

import threading

def my_thread():
    print("Thread running")

thread = threading.Thread(target=my_thread)
thread.start()
thread.join()

54. 多进程:

import multiprocessing
def my_process():
    print("Process running")
process = multiprocessing.Process(target=my_process)
process.start()
process.join()

55. 进程池:

from multiprocessing import Pool
def my_function(x):
    return x*x
with Pool(5) as p:
    print(p.map(my_function, [1, 2, 3]))

56. 队列:

from queue import Queue
q = Queue()
q.put(1)
q.put(2)
q.get()

57. 协程:

import asyncio
async def my_coroutine():
    await asyncio.sleep(1)
    print("Coroutine running")

asyncio.run(my_coroutine())

58. 异步IO:

import aiohttp
import asyncio

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

loop = asyncio.get_event_loop()
loop.run_until_complete(fetch("https://www.example.com"))

59. 信号处理:

import signal


def handler(signum, frame):
    print("Signal handler called with signal", signum)

signal.signal(signal.SIGINT, handler)

60. 装饰器的实现:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before function call")
        result = func(*args, **kwargs)
        print("After function call")
        return result
    return wrapper

61. 基于类的装饰器:

class MyDecorator:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        print("Before function call")
        result = self.func(*args, **kwargs)
        print("After function call")
        return result

62. 模块和包的导入:

from my_package import my_module

63. 相对导入:

from .my_module import my_function

64. 集合操作:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
set1 & set2  # 交集
set1 | set2  # 并集
set1 - set2  # 差集

65. 集合方法:

my_set.add(5)
my_set.remove(5)

66. 字典方法:

my_dict.keys()
my_dict.values()
my_dict.items()

67. 对象方法:

class MyClass:
    def method(self):
        pass

obj = MyClass()
obj.method()

68. 类方法:

class MyClass:
    @classmethod
    def method(cls):
        pass

69. 静态方法:

class MyClass:
    @staticmethod
    def method():
        pass

70. 上下文管理器的实现:

class MyContextManager:
    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

with MyContextManager():
    pass

71. 元类:

class MyMeta(type):
    def __new__(cls, name, bases, dct):
        return super().__new__(cls, name, bases, dct)

72. 装饰器链:

@decorator1
@decorator2
def my_function():
    pass

73. 属性的getter和setter:

class MyClass:
    def __init__(self, value):
        self._value = value
    @property
    def value(self):
        return self._value
    @value.setter
    def value(self, new_value):
        self._value = new_value

74. 文件操作:

with open("file.txt", "r") as file:
    content = file.read()

75. with语句:

with open("file.txt", "r") as file:
    content = file.read()

76. yield语句:

def my_generator():
    yield 1
    yield 2
    yield 3

77. 生成器表达式:

gen = (x**2 for x in range(10))

78. 列表方法:

my_list.append(5)
my_list.remove(5)

79. 元组解包:

a, b, c = (1, 2, 3)

80. 字典解包:

def my_function(a, b, c):
    pass

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_function(**my_dict)

81. 循环中断:

for i in range(10):
    if i == 5:
        break

82. 循环跳过:

for i in range(10):
    if i == 5:
        continue

83. 异步编程:

import asyncio

async def my_coroutine():
    await asyncio.sleep(1)

asyncio.run(my_coroutine())

84. 类型检查:

isinstance(5, int)

85. 序列化和反序列化:

import pickle
data = {"name": "John", "age": 30}
with open("data.pkl", "wb") as file:
    pickle.dump(data, file)

with open("data.pkl", "rb") as file:
    data = pickle.load(file)

86. 文件读取模式:

with open("file.txt", "r") as file:
    content = file.read()

87. 文件写入模式:

with open("file.txt", "w") as file:
    file.write("Hello, World!")

88. 上下文管理器:

with open("file.txt", "r") as file:
    content = file.read()

89. 命令行参数解析:

import argparse

parser = argparse.ArgumentParser(description="My program")
parser.add_argument("name", type=str, help="Your name")
args = parser.parse_args()

90. 模块导入:

import my_module

91. 包导入:

from my_package import my_module

92. 包的相对导入:

from .my_module import my_function

93. 动态属性:

class MyClass:
    def __init__(self):
        self.dynamic_attr = "I am dynamic"

94. 动态方法:

def dynamic_method(self):
    return "I am dynamic"

MyClass.dynamic_method = dynamic_method

95. 类的单例模式:

class Singleton:
    _instance = None

96. 类的工厂模式:

class Factory:
    def create(self, type):
        if type == "A":
            return A()
        elif type == "B":
            return B()

97. 依赖注入:

class Service:
    def __init__(self, dependency):
        self.dependency = dependency

98. 抽象类:

from abc import ABC, abstractmethod
class AbstractClass(ABC):
    @abstractmethod
    def my_method(self):
        pass

99. 接口:

from abc import ABC, abstractmethod
class Interface(ABC):
    @abstractmethod
    def method(self):
        pass

相关推荐

Github霸榜的SpringBoot全套学习教程,从入门到实战,内容超详细

前言...

SpringBoot+LayUI后台管理系统开发脚手架

源码获取方式:关注,转发之后私信回复【源码】即可免费获取到!项目简介本项目本着避免重复造轮子的原则,建立一套快速开发JavaWEB项目(springboot-mini),能满足大部分后台管理系统基础开...

Spring Boot+Vue全栈开发实战,中文版高清PDF资源

SpringBoot+Vue全栈开发实战,中文高清PDF资源,需要的可以私我:)SpringBoot致力于简化开发配置并为企业级开发提供一系列非业务性功能,而Vue则采用数据驱动视图的方式将程序...

2021年超详细的java学习路线总结—纯干货分享

本文整理了java开发的学习路线和相关的学习资源,非常适合零基础入门java的同学,希望大家在学习的时候,能够节省时间。纯干货,良心推荐!第一阶段:Java基础...

探秘Spring Cache:让Java应用飞起来的秘密武器

探秘SpringCache:让Java应用飞起来的秘密武器在当今快节奏的软件开发环境中,性能优化显得尤为重要。SpringCache作为Spring框架的一部分,为我们提供了强大的缓存管理能力,让...

3,从零开始搭建SSHM开发框架(集成Spring MVC)

目录本专题博客已共享在(这个可能会更新的稍微一些)https://code.csdn.net/yangwei19680827/maven_sshm_blog...

Spring Boot中如何使用缓存?超简单

SpringBoot中的缓存可以减少从数据库重复获取数据或执行昂贵计算的需要,从而显著提高应用程序的性能。SpringBoot提供了与各种缓存提供程序的集成,您可以在应用程序中轻松配置和使用缓...

我敢保证,全网没有再比这更详细的Java知识点总结了,送你啊

接下来你看到的将是全网最详细的Java知识点总结,全文分为三大部分:Java基础、Java框架、Java+云数据小编将为大家仔细讲解每大部分里面的详细知识点,别眨眼,从小白到大佬、零基础到精通,你绝...

1,从零开始搭建SSHM开发框架(环境准备)

目录本专题博客已共享在https://code.csdn.net/yangwei19680827/maven_sshm_blog1,从零开始搭建SSHM开发框架(环境准备)...

做一个适合二次开发的低代码平台,把程序员从curd中解脱出来-1

干程序员也有好长时间了,大多数时间都是在做curd。现在想做一个通用的curd平台直接将我们解放出来;把核心放在业务处理中。用过代码生成器,在数据表设计好之后使用它就可以生成需要的controller...

设计一个高性能Java Web框架(java做网站的框架)

设计一个高性能JavaWeb框架在当今互联网高速发展的时代,构建高性能的JavaWeb框架对于提升用户体验至关重要。本文将从多个角度探讨如何设计这样一个框架,让我们一起进入这段充满挑战和乐趣的旅程...

【推荐】强&牛!一款开源免费的功能强大的代码生成器系统!

今天,给大家推荐一个代码生成器系统项目,这个项目目前收获了5.3KStar,个人觉得不错,值得拿出来和大家分享下。这是我目前见过最好的代码生成器系统项目。功能完整,代码结构清晰。...

Java面试题及答案总结(2025版持续更新)

大家好,我是Java面试分享最近很多小伙伴在忙着找工作,给大家整理了一份非常全面的Java面试场景题及答案。...

Java开发网站架构演变过程-从单体应用到微服务架构详解

Java开发网站架构演变过程,到目前为止,大致分为5个阶段,分别为单体架构、集群架构、分布式架构、SOA架构和微服务架构。下面玄武老师来给大家详细介绍下这5种架构模式的发展背景、各自优缺点以及涉及到的...

本地缓存GuavaCache(一)(guava本地缓存原理)

在并发量、吞吐量越来越大的情况下往往是离不开缓存的,使用缓存能减轻数据库的压力,临时存储数据。根据不同的场景选择不同的缓存,分布式缓存有Redis,Memcached、Tair、EVCache、Aer...