Python 中的抽象方法

89 阅读2分钟

在一个 Python 项目中,遇到一个 TilePuzzleProblem 类,该类继承自 search.Problem 类,用于解决 NxN-空格拼图问题。在 TilePuzzleProblem 类中,有两个方法被标记为 abstract,分别是 successor 和 h。当尝试运行代码时,程序会在 abstract 部分挂起。

huake_00152_.jpg 2. 解决方案

根据 Python 中抽象方法的含义,有以下几种解决方案:

解决方案 1:

创建 TilePuzzleProblem 的子类,并为 successor 和 h 方法提供具体的实现。例如:

class MyTilePuzzleProblem(TilePuzzleProblem):
    def successor(self, state):
        # Provide an implementation for the successor method

    def h(self, node):
        # Provide an implementation for the h method

解决方案 2:

如果不需要使用 successor 和 h 方法,可以将 abstract 关键字替换为 pass,这样就不会抛出 NotImplementedError 异常。例如:

class TilePuzzleProblem(search.Problem):
    """ This class is the class for the NxN - blanks tile puzzle problem """

    def __init__(self, N, blanks, initial, goal):
        """ Initialize """
        search.Problem.__init__(self, initial, goal)
        self.N = N
        self.blanks = blanks

    def successor(self, state):
        pass

    def h(self, node):
        pass

解决方案 3:

如果需要保留 abstract 关键字,可以使用 Python 中的 @abstractmethod 装饰器来标记抽象方法,并使用 abc 模块来定义一个抽象基类。例如:

from abc import ABC, abstractmethod

class TilePuzzleProblem(ABC):
    """ This class is the abstract base class for the NxN - blanks tile puzzle problem """

    def __init__(self, N, blanks, initial, goal):
        """ Initialize """
        super().__init__()
        self.N = N
        self.blanks = blanks

    @abstractmethod
    def successor(self, state):
        """ Generate the successors of the given state. Returns a list of (move, successor) pairs"""

    @abstractmethod
    def h(self, node):
        """ Heuristic function """

不同的解决方案的代码例子如下:

  • 解决方案 1:
class MyTilePuzzleProblem(TilePuzzleProblem):
    def successor(self, state):
        # Provide an implementation for the successor method

    def h(self, node):
        # Provide an implementation for the h method
  • 解决方案 2:
class TilePuzzleProblem(search.Problem):
    """ This class is the class for the NxN - blanks tile puzzle problem """

    def __init__(self, N, blanks, initial, goal):
        """ Initialize """
        search.Problem.__init__(self, initial, goal)
        self.N = N
        self.blanks = blanks

    def successor(self, state):
        pass

    def h(self, node):
        pass
  • 解决方案 3:
from abc import ABC, abstractmethod

class TilePuzzleProblem(ABC):
    """ This class is the abstract base class for the NxN - blanks tile puzzle problem """

    def __init__(self, N, blanks, initial, goal):
        """ Initialize """
        super().__init__()
        self.N = N
        self.blanks = blanks

    @abstractmethod
    def successor(self, state):
        """ Generate the successors of the given state. Returns a list of (move, successor) pairs"""

    @abstractmethod
    def h(self, node):
        """ Heuristic function """