下一篇:Python基础篇_修饰符(Decorators)【中】@property、@<attribute_name>.setter、@<attribute_name>.deleter、@functools.lru_cache(maxsize=None)
Python基础篇_修饰符(Decorators)【上】
Python基础篇_修饰符【上】
Python中有多种修饰符,这些修饰符用于指定方法的特殊行为或属性,也是用于修改函数行为的特殊参数。
一、修饰符一般特点
- 修饰符只能用于类定义中,不能用于普通函数中
- 属性修饰符是可叠加的,也就是说,一个方法可以同时被多个属性修饰符修饰
二、常用的修饰符以及用法举例
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 ~