我发布这个问题是因为我在其他地方找不到明确的答案
考虑下面的Python代码:
from dataclasses import dataclass, field
from typing import List
@dataclass
class ShoppingItem:
name: str
price: float
@dataclass
class ShoppingCart:
items: List[ShoppingItem]
discount: float = field(default=0)
def __post_init__(self):
self.items.sort(key=lambda item: item.price)
def total_price(self):
return (1 - self.discount) * sum(item.price for item in self.items)
def __getitem__(self, key):
return self.items[key]
使用方括号操作符,可以从购物车中获取特定的商品
cart = ShoppingCart(
items=[
ShoppingItem(name="Shirt", price=100),
ShoppingItem(name="Pants", price=120),
ShoppingItem(name="Socks", price=40),
ShoppingItem(name="Shoes", price=80),
]
)
print(cart[1]) # Will print Shoes
现在,让我们考虑使用切片操作符来获取购物车的一个子集(因为我们只想购买3个最贵的商品),但是我们希望输出是一个^ {< CD1>}(因为我们希望保持折扣)。如果我们使用上面的实现,结果对象将是list
,而不是ShoppingCart
:
most_expensive = cart[-3:] # returns a list, not a ShoppingCart
如何重写切片运算符以返回ShoppingCart
,而保留简单的方括号运算符以返回ShoppingItem
虽然在Python2.7中有
__getslice__
魔术方法专门用于覆盖切片,但在Python3中,这种方法被弃用,只使用__getitem__
因此,当重写方括号运算符时,可以检查输入是否为
slice
对象,然后确保返回的项与预期的一样。在我们的示例中,它应该如下所示:相关问题 更多 >
编程相关推荐