Python 重载 show 方法,实现电池价格单独显示

在 Python 中,我们可以通过重载方法来实现对不同情况的处理。以下示例代码展示了如何重载 show 方法,使其可以根据参数选择是否只显示电池价格。

class Battery:
    def __init__(self, brand, model, capacity, price):
        self.brand = brand
        self.model = model
        self.capacity = capacity
        self.price = price

    def show(self):
        print(f'Battery: {self.brand} {self.model}, {self.capacity}mAh, ${self.price}')

    def __str__(self):
        return f'{self.brand} {self.model}, {self.capacity}mAh, ${self.price}'

    def __repr__(self):
        return self.__str__()

    def __add__(self, other):
        total_capacity = self.capacity + other.capacity
        total_price = self.price + other.price
        return Battery('Combined', f'{self.model} + {other.model}', total_capacity, total_price)

    # 重载 show 方法,只显示价格
    def show(self, price_only=True):
        if price_only:
            print(f'Price: ${self.price}')
        else:
            print(self)

在上面的示例代码中,我们重载了 show 方法,添加了一个 price_only 参数。当 price_onlyTrue 时,只显示电池价格;否则,显示完整的电池信息。

通过重载方法,我们可以根据不同的需求,实现不同的功能,使代码更加灵活和可读。

Python 重载 show 方法,实现电池价格单独显示

原文地址: https://www.cveoy.top/t/topic/m1k5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录