python中的父/子类结构

时间:2019-06-09 17:41:07

标签: python class inheritance superclass

我目前正在使用一种定价工具,该工具具有多个计算级别。

例如,我有一个对象Quote,它本身附加了一个或多个QuoteItem。

我认为应该继承类,但是我不想每次创建QuoteItem时都初始化自己的Quote,因为所有QuoteItem都共享具有相同特征的完全相同的Quote。

那是具有超类的类继承吗?还是应该是2个独立班级? 我找不到关于我的场景的任何文档或资源,我认为这很常见。

我有一个附加在一个引号上的引号项目列表,我想先创建引号,然后再创建引号。如果我从引号开始,我觉得它将每次都创建一个完全不是预期行为的引号,因为所有引号都应该只有一个引号。

这是正确的方法吗?

class Quote():
    def __init__():
        # this will set parameter global to the quote
        print('Quote created')


class QuoteItem(Quote):
    def __init__():
        # this will set specific details for all quote items attached to one specific quote
        print ('QuoteItem created')

或者这两个类应该完全独立吗?

欢迎使用案例或有关此类场景的文档。 我发现的父级/子类文档仅处理非常相似的对象。在我的示例中,它们是不一样的,它们是子代,即,没有引号的引号就不可能存在。

谢谢

2 个答案:

答案 0 :(得分:2)

在这里使用继承并不是最好的方法。只需让Quote有一个包含所有QuoteItems的容器(例如列表)即可。

当使用这样的继承时,您是说QuoteItemQuote的一种特殊类型,不是。 QuoteItemQuote的一部分。

答案 1 :(得分:2)

考虑继承时,您使用的是“是”关系。

class Vehicle(object):  # a Vehicle IS AN object
    pass
class Car(Vehicle):     # a Car     IS A  Vehicle
    pass
class Sedan(Car):       # A Sedan   IS A  Car
    pass

您可能在报价及其项目中查找的是“具有”关系。

class Tire(object):     # a Tire IS AN object, but...
    pass

class Vehicle(object):
    def __init__(self, num_tires=4):
        self.tires = [Tire() for _ in num_tires]
                        # a Vehicle HAS A Tire  (or in this case 4 tires)

要针对您的特定用例扩展隐喻:

class QuoteItem(object):
    def __init__(self, modelnumber, quantity, totalprice):
        self.modelnumber = modelnumber
        self.quantity = quantity
        self.totalprice = totalprice
        # I'm guessing at what you'd want here


class Quote(object):
    _last_quote_number = 0

    @property
    @classmethod
    def next_quote_number(cls) -> int:
        cls._last_quote_number += 1
        return cls._last_quote_number

    def __init__(self, customerid):
        self.number = self.next_quote_number
        self.customerid = customerid
        self.items = []

    def add_item(self, modelnumber, quantity, totalprice) -> None:
        item = QuoteItem(modelnumber, quantity, totalprice)
        self.items.append(item)