0

我想从抽象类方法中调用被覆盖的抽象类方法(子类方法),但是遇到了几个错误。请问你能帮帮我吗?我的概念:

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)

因此,它将使用覆盖 BaseClass 方法的子类方法 B.basic_format。

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

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

我认为这个问题可以参考,baseClass中引用了basic_format。但是如何绕过呢?

4

0 回答 0