class Product:
def __init__(self, name, price, cost_price):
self.name = name
self.price = price
self.cost_price = cost_price
def getDetails(self):
return f"Name: {self.name}, Price: {self.price}"
def role_based_decorator(role):
def decorator(cls):
def new_getDetails(self):
if role == 'admin':
return f"Name: {self.name}, Price: {self.price}, Cost Price: {self.cost_price}"
elif role == 'customer':
return f"Name: {self.name}, Price: {self.price}"
else:
return "Invalid role"
cls.getDetails = new_getDetails
return cls
return decorator
# 应用装饰器
@role_based_decorator('admin')
class AdminProduct(Product):
pass
@role_based_decorator('customer')
class CustomerProduct(Product):
pass
# 测试
admin_product = AdminProduct("Sample Product", 100, 50)
print(admin_product.getDetails())
customer_product = CustomerProduct("Sample Product", 100, 50)
print(customer_product.getDetails())
设计思路
- Product类:定义了商品的基本属性
name
、price
、cost_price
和方法getDetails
,初始的getDetails
方法返回商品名称和售价。
- 装饰器:
role_based_decorator
是一个类装饰器,接收一个role
参数。它返回一个内部装饰器decorator
,该内部装饰器接收一个类cls
作为参数。在内部装饰器中,定义了一个新的getDetails
方法,根据传入的role
决定返回商品的详细信息。然后将新的getDetails
方法替换原类的getDetails
方法,并返回修改后的类。
- 应用装饰器:通过
@role_based_decorator('admin')
和@role_based_decorator('customer')
分别对Product
类进行装饰,创建出AdminProduct
和CustomerProduct
类,它们的getDetails
方法根据不同角色有不同的行为。