十个python高级代码片段(Ⅱ)

1. Python 中的单例模式

class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance

singleton1 = Singleton()
singleton2 = Singleton()

print(singleton1 is singleton2)  # 输出: True

说明: 单例模式确保一个类只有一个实例,并提供一个全局访问点。以上代码实现了一个简单的单例模式。

2. 鸭子类型与动态特性

class Duck:
    def quack(self):
        print("Quack!")

class Dog:
    def quack(self):
        print("Woof!")

def make_it_quack(animal):
    animal.quack()

duck = Duck()
dog = Dog()

make_it_quack(duck)  # 输出: Quack!
make_it_quack(dog)   # 输出: Woof!

说明: Python的鸭子类型特性允许只要对象看起来像鸭子(即有quack方法),就可以被认为是鸭子。这种动态特性使代码更加灵活。

3. 偏函数

from functools import partial

def power(base, exponent):
    return base ** exponent

square = partial(power, exponent=2)
cube = partial(power, exponent=3)

print(square(5))  # 输出: 25
print(cube(5))    # 输出: 125

说明: 偏函数允许创建一个新的函数,它固定了原函数的一些参数。这里partial创建了squarecube,分别计算平方和立方。

4. 属性装饰器

class Celsius:
    def __init__(self, temperature=0):
        self._temperature = temperature

    @property
    def temperature(self):
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        if value < -273.15:
            raise ValueError("Temperature below -273.15 is not possible")
        self._temperature = value

temp = Celsius()
temp.temperature = 25
print(temp.temperature)  # 输出: 25

说明: 使用@property装饰器创建属性访问器,使得类属性的访问和修改具有方法的特性,同时保留属性的简单语法。

5. 自定义异常

class CustomError(Exception):
    def __init__(self, message):
        self.message = message

def some_function():
    raise CustomError("Something went wrong")

try:
    some_function()
except CustomError as e:
    print(e.message)  # 输出: Something went wrong

说明: 自定义异常类允许开发者定义更精确的错误类型和信息,以便更好地处理异常。

6. 数据类

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p = Point(10, 20)
print(p)  # 输出: Point(x=10, y=20)

说明: 使用@dataclass装饰器可以简化类的定义,自动生成__init____repr__等方法,特别适合用于存储数据的简单类。

7. 闭包

def outer_function(msg):
    def inner_function():
        print(msg)
    return inner_function

hello_func = outer_function("Hello")
hello_func()  # 输出: Hello

说明: 闭包是指内部函数对外部函数作用域的变量的引用,尽管外部函数已经返回,内部函数仍然可以访问这些变量。

8. 装饰器链

def decorator_one(func):
    def wrapper(*args, **kwargs):
        print("Decorator One")
        return func(*args, **kwargs)
    return wrapper

def decorator_two(func):
    def wrapper(*args, **kwargs):
        print("Decorator Two")
        return func(*args, **kwargs)
    return wrapper

@decorator_one
@decorator_two
def greet(name):
    print(f"Hello, {name}")

greet("Alice")
# 输出:
# Decorator One
# Decorator Two
# Hello, Alice

说明: 装饰器链是指多个装饰器作用于同一个函数,按照从内向外的顺序执行。

9. 上下文管理器 for 数据库连接

import sqlite3

class Database:
    def __init__(self, db_name):
        self.db_name = db_name

    def __enter__(self):
        self.conn = sqlite3.connect(self.db_name)
        return self.conn

    def __exit__(self, exc_type, exc_value, traceback):
        self.conn.close()

with Database('test.db') as conn:
    cursor = conn.cursor()
    cursor.execute('CREATE TABLE IF NOT EXISTS person (id INTEGER PRIMARY KEY, name TEXT)')
    conn.commit()

说明: 上下文管理器用于自动管理数据库连接的打开和关闭,确保资源不被泄露。

10. 使用类方法创建工厂函数

class Pizza:
    def __init__(self, ingredients):
        self.ingredients = ingredients

    @classmethod
    def margherita(cls):
        return cls(['mozzarella', 'tomatoes'])

    @classmethod
    def prosciutto(cls):
        return cls(['mozzarella', 'tomatoes', 'ham'])

print(Pizza.margherita().ingredients)  # 输出: ['mozzarella', 'tomatoes']
print(Pizza.prosciutto().ingredients)  # 输出: ['mozzarella', 'tomatoes', 'ham']

说明: 类方法通常用于实现工厂函数,提供一种替代构造方法的对象创建方式。这种方式更清晰、更具可读性,特别是当需要创建多种配置的对象时。

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值