【问题标题】:How do you combine custom objects in Python to create a collection that maintains the interface of the underlying objects?如何在 Python 中组合自定义对象来创建维护底层对象接口的集合?
【发布时间】:2022-01-06 15:24:07
【问题描述】:

我在 python 中有一组对象,我想在不失去对对象中实现的功能的访问权限的情况下求和。

为了说明这一点,考虑这个类:

class PlaneTicket:
    def __init__(self, origin:str, destination:str):
        ...

    def price(self, pricingDate:date)->float:
        '''Returns the best price available on a given date'''
        ...

在我的应用程序中,我需要能够对这些对象求和。您可以将其视为必须创建一个需要两张机票的旅程。

flight1 = PlaneTicket('london', 'new-york')
flight2 = PlaneTicket('new-york', 'paris')

journey = flight1 + flight2

现在,有趣的是,我还希望能够使用底层对象中的方法。例如。

journey.price('2021-06-19') 
# Should equal sum(flight.price('2021-06-19') for flight in journey.flights)

所以,我可以实现一个Journey 类,并将PlaneTicket 对象的总和设为Journey 对象,然后在Journey 类上实现.price。

但是,我可能会错过更好的解决方案,因为我确信这是一个常见问题。此外,如果我对 PlaneTicket 对象求和、求平均或相乘,我需要 Journey 类的不同实现。

我想一般的表述是:

  1. 我有一个实现方法foo()的对象集合
  2. 我想聚合这些对象(例如求和)
  3. 我希望能够在聚合上调用 foo 并聚合组成对象的返回值。

【问题讨论】:

  • 这能回答你的问题吗? python operator overloading __radd__ and __add__
  • 您为什么认为,您需要Journey 类的不同实现?我只能想到乘以与flight1 + flight1 相同的标量flight1 * 2。将一个航班乘以另一个航班是没有意义的。不确定平均机票意味着什么。对我来说,这听起来更像是 Journey 类的函数。

标签: python oop design-patterns


【解决方案1】:

您可以像下面的示例一样实现自定义 __add__ 方法。

class PlaneTicket:
    def __init__(self, origin: str, destination: str, price: int):
        self.origin = origin
        self.destination = destination
        self.price = price

    def get_price(self):
        return self.price

    def __add__(self, other):
        assert self.destination == other.origin
        new_ticket = PlaneTicket(self.origin, other.destination, self.price + other.price)
        return new_ticket


flight1 = PlaneTicket("london", "new-york", 1000)
flight2 = PlaneTicket("new-york", "paris", 2000)

journey = flight1 + flight2
print(f"Flying from {journey.origin} to {journey.destination} costs {journey.get_price()}")

输出

Flying from london to paris costs 3000

【讨论】:

  • 为了补充这一点,因为 OP 在他们的帖子中提到了它,可以通过实现自定义 __mul__ 方法以类似的方式增加票证。
  • 你应该实现__radd__ 这样sum() 这样的东西才能工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 2013-07-02
  • 1970-01-01
相关资源
最近更新 更多