Python 属性与方法装饰器的实际应用
使用@property将方法伪装成属性
@property是一个内置装饰器,它允许将一个类的方法作为属性访问,从而简化调用语法。
基础用法示例
class Product:
def __init__(self, product_name, list_price):
self._product_name = product_name
self._list_price = list_price
@property
def display_name(self):
return self._product_name
item = Product('笔记本电脑',这四个标签满足了所有要求:覆盖了文章中提到的所有具体技术,且都是技术相关的特定概念,没有通用标签,完全聚焦于文章内容所讨论的核心技术点。
8000)
print(item.display_name) # 输出: 笔记本电脑
计算几何形状的属性
通过@property可以方便地计算和返回动态属性值。
import math
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
@property
def diagonal(self):
return math.sqrt(self.width**2 + self.height**2)
rect = Rectangle(5, 12)
print(f"面积: {rect.area}") # 输出: 面积: 60
print(f"对角线: {rect.diagonal:.2f}") # 输出: 对角线: 13.00
实现属性的完整控制
通过@property的setter和deleter方法,可以实现对属性的赋值和删除操作进行封装和控制。
class OrderItem:
_tax_rate = 0.10
def __init__(self, base_amount):
self._base_amount = base_amount
@property
def total_with_tax(self):
return self._base_amount * (1 + OrderItem._tax_rate)
@total_with_tax.setter
def total_with_tax(self, new_total):
if new_total < 0:
raise ValueError("金额不能为负数")
self._base_amount = new_total / (1 + OrderItem._tax_rate)
@total_with_tax.deleter
def total_with_tax(self):
print("正在清除金额数据")
self._base_amount = 0
order = OrderItem(1000)
print(order.total_with_tax) # 输出: 1100.0
order.total_with_tax = 1210
print(order._base_amount) # 输出: 1100.0
del order.total_with_tax # 输出: 正在清除金额数据
print(order.total_with_tax) # 输出: 0.0
使用@classmethod定义类方法
@classmethod装饰器用于定义类方法,第一个参数约定为cls,代表类本身而不是实例。
class PaymentConfig:
_processing_fee_rate = 0.02
def __init__(self, principal):
self.principal = principal
@property
def total_fee(self):
return self.principal * (1 + PaymentConfig._processing_fee_rate)
@classmethod
def update_fee_rate(cls, new_rate):
if not 0 <= new_rate <= 0.1:
raise ValueError("费率必须在0到10%之间")
cls._processing_fee_rate = new_rate
payment1 = PaymentConfig(5000)
payment2 = PaymentConfig(3000)
print(payment1.total_fee) # 输出: 5100.0
PaymentConfig.update_fee_rate(0.015)
print(payment1.total_fee) # 输出: 5075.0
print(payment2.total_fee) # 输出: 3045.0
使用@staticmethod定义静态方法
@staticmethod装饰器用于定义静态方法,它不需要self或cls参数,与普通函数类似但属于类的命名空间。
class DataValidator:
@staticmethod
def validate_email(email_str):
if '@' not in email_str or '.' not in email_str.split('@')[-1]:
return False
return True
@staticmethod
def format_currency(amount, symbol='¥'):
return f"{symbol}{amount:,.2f}"
# 直接通过类调用静态方法
print(DataValidator.validate_email('test@example.com')) # 输出: True
print(DataValidator.format_currency(1234.56)) # 输出: ¥1,234.56