Python基础篇_修饰符(Decorators)【上】

本文详细介绍了Python中的修饰符,包括装饰器的使用示例、类方法(@classmethod)如何访问类属性及实例化,以及静态方法(@staticmethod)的特点和应用。通过实例演示了如何利用这些修饰符改变函数行为和访问类特性。
摘要由CSDN通过智能技术生成

下一篇:Python基础篇_修饰符(Decorators)【中】@property、@<attribute_name>.setter、@<attribute_name>.deleter、@functools.lru_cache(maxsize=None)

Python基础篇_修饰符【上】

    Python中有多种修饰符,这些修饰符用于指定方法的特殊行为或属性,也是用于修改函数行为的特殊参数。

一、修饰符一般特点

  1. 修饰符只能用于类定义中,不能用于普通函数中
  2. 属性修饰符是可叠加的,也就是说,一个方法可以同时被多个属性修饰符修饰

二、常用的修饰符以及用法举例

1) @decorator,装饰器

    @decorator装饰器是一种修改函数行为的特殊函数,它接受一个函数作为参数,并返回一个新的函数。通过在函数声明前加上 @decorator 修饰符,可以将装饰器应用于该函数。

示例1:使用装饰器打印函数执行时间

import time

def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Function {func.__name__} took {end_time - start_time} seconds to execute.")
        return result
    return wrapper

@timer_decorator
def my_function():
    time.sleep(2)  # 模拟耗时操作
    return "Hello, World!"

result = my_function()
print(result)  # 输出:Hello, World!
print(f"Function {my_function.__name__} took {time.time() - end_time} seconds to execute.")  # 输出:Function my_function took 2.0003339641967773 seconds to execute.

示例2:使用装饰器检查函数参数类型

def check_params_decorator(func):
    def wrapper(*args, **kwargs):
        for arg in args:
            if not isinstance(arg, int):
                raise ValueError("All arguments must be integers.")
        for key, value in kwargs.items():
            if not isinstance(value, int):
                raise ValueError(f"{key} must be an integer.")
        return func(*args, **kwargs)
    return wrapper

@check_params_decorator
def my_function(a, b, c=3):
    return a + b + c

result = my_function(1, 2, 4)  # 输出:6
result = my_function(1, "2", 4)  # 抛出 ValueError 异常:All arguments must be integers.

示例3:使用装饰器检查函数返回值类型

def check_return_value_decorator(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if not isinstance(result, int):
            raise ValueError("The function must return an integer.")
        return result
    return wrapper

@check_return_value_decorator
def my_function():
    return "Hello, World!"  # 抛出 ValueError 异常:The function must return an integer.

2) @classmethod,类方法

    @classmethod: 用于定义类方法,类方法可以访问和修改类属性,可以通过类来调用,不需要实例化对象。类方法的第一个参数通常被命名为cls,表示类本身

示例1:使用类方法计算两个数的和

class Calculator:
    @classmethod
    def add(cls, x, y):
        return x + y

result = Calculator.add(2, 3)
print(result)  # 输出:5

示例2:使用类方法访问类的静态属性

class MyClass:
    value = 10

    @classmethod
    def get_value(cls):
        return cls.value

result = MyClass.get_value()
print(result)  # 输出:10

示例3:使用类方法实现类的工厂方法模式

class Shape:
    @classmethod
    def create(cls, name):
        if name == "Circle":
            return cls()._create_circle()
        elif name == "Square":
            return cls()._create_square()
        else:
            raise ValueError("Invalid shape name.")

    def _create_circle(self):
        return "Circle"

    def _create_square(self):
        return "Square"

在这个示例中,Shape 类定义了一个 create 类方法,它根据传入的名称参数返回不同类型的形状。
通过调用 Shape 类的 create 方法,可以创建不同类型的形状对象。
如果传入的名称参数无效,则抛出 ValueError 异常。

3) @staticmethod,静态方法

    静态方法是一种不需要实例化对象就可以调用的方法,它与类关联而不是与实例关联,静态方法既不访问实例属性,也不访问类属性,更不需要实例化对象即可调用。它在类中的定义类似于普通函数;静态方法的不需要self参数;

示例1:使用静态方法计算两个数的乘积

class Calculator:
    @staticmethod
    def multiply(x, y):
        return x * y

result = Calculator.multiply(2, 3)
print(result)  # 输出:6

示例2:使用静态方法获取类的静态属性

class MyClass:
    value = 10

    @staticmethod
    def get_value():
        return MyClass.value

result = MyClass.get_value()
print(result)  # 输出:10

示例3:使用静态方法执行无参操作

class FileOperation:
    @staticmethod
    def log_message(message):
        print(message)

FileOperation.log_message("Hello, World!")  # 输出:Hello, World!

may the odds be ever in your favor ~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长孤秋落

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值