从python中的抽象类方法调用子类方法(重写的抽象类方法)

时间:2015-01-14 12:00:19

标签: python inheritance abstract-class subclass abc

我想从抽象类方法中调用重写的抽象类方法(子类方法),但是会出现几个错误。请问你能帮帮我吗? 我的理念:

import abc
from my_module import Format, Message

class BaseClass(object):
    """
    Object getting some messages and modifying them. Some modify functions differ
     subclass to subclass.

    """

    __metaclass__ = abc.ABCMeta

    @classmethod
    @abc.abstractmethod
    def basic_format(cls, msg_):
        """Dynamically creates new format.
        To be overridden in subclasses.

        """
        raise NotImplementedError

    message_formats_dict = {0x00: Format(basic_format)}

    @classmethod
    @abc.abstractmethod
    def modify(cls, msg_type_id_, msg_, new_format_=None):
        """
        Class method returning modified message according to given function.

            :param int msg_type_id_: Message type.

            :param msg_: Message to be changed.

            :param new_format_: New format or a function defining
                                it dynamically

            :returns: Modified message.

        """
        if new_format_:
            cls.message_formats_dict.update((msg_type_id_, new_format_))

        return cls.message_formats_dict[msg_type_id_].produce_formatted_msg(msg_)

class B(BaseClass):
    """
    Subclass of A.

    """

    @classmethod
    def basic_format(cls, msg_):
        """Overrides the BaseClass.basic_format, creates basic format for B
        type.

        """
        return Format(msg_[3], msg_[2], msg_[1])

    @classmethod
    def format_01(cls, msg_):
        """Creates format_01 for B type.

        """
        return Format(msg_[2], msg_[1], msg_[3])

    @classmethod
    def modify(cls, msg_type_id_, msg_, new_format_=None):
        """Overrides the BaseClass.modify, adds new function.

        """
        cls.message_formats_dict.update((0x01, format_01))

        return super(B, cls).modify(cls, msg_type_id_, msg_, new_format_)

好吧,我想在课堂上和实例上都这样说:

new_message_01 = B.modify(0x00, some_message)
new_message_02 = B().modify(0x00, some_message)

所以,它会使用子类方法B.basic_format重写BaseClass方法。

调用在子类B中实现并从B引用的format_01方法可以正常工作:

new_message_03 = B.modify(0x01, some_message)
new_message_04 = B().modify(0x01, some_message)

我认为问题可以参考,basic_format在BaseClass中引用。但是怎么通过呢?

0 个答案:

没有答案