如何引用超类中的子类?

时间:2018-11-10 22:03:24

标签: python

我正在定义一个Python Holiday类和三个子类:一个用于固定日期假日,第二个用于相对假日,第三个用于浮动星期一假日。我想在超类Holiday中创建一组常量,以便应用程序可以简单地将特定假期称为

Holiday.NEW_YEARS
Holiday.CHRISTMAS
etc.

,但是当实例化父类时,子类显然不存在。我该怎么办?

class Holiday(object):
    NEW_YEARS = FixedHoliday(1, 1)
    MLK_BIRTHDAY = FloatingMonday(1, 15)
    ...

2 个答案:

答案 0 :(得分:0)

一个类不能也不应引用其派生类。尝试以下方法:

Shape

答案 1 :(得分:0)

一种实现方法是在定义基类和所有子类之后装饰基类。您可以在Python中做到这一点,因为类是可变对象。

这是我的建议:

class Holiday:
    def __init__(self, month, day):
        self.month, self.day = month, day

    def __repr__(self):
        return '{}(month={}, day={})'.format(type(self).__name__, self.month, self.day)

class FixedHoliday(Holiday):
    pass

class FloatingMonday(Holiday):
    pass

#class MondayHoliday(Holiday): ... etc    


# Base class decorator.
def inject_constants(cls):
    """ Add attributes to class. """
    HOLIDATA = {
        'NEW_YEARS': FixedHoliday(1, 1),
        'MLK_BIRTHDAY': FloatingMonday(1, 15)
    }

    for key, value in HOLIDATA.items():
        setattr(cls, key, value)


inject_constants(Holiday)

print(Holiday.NEW_YEARS)    # -> FixedHoliday(month=1, day=1)
print(Holiday.MLK_BIRTHDAY) # -> FloatingMonday(month=1, day=15)