首页 > 解决方案 > 在抽象类的情况下,实例化的最佳方式是什么?

问题描述

根据我目前的理解(注意告诉我我的话定义的正确性):我们应该在抽象类中声明我们的抽象方法,并将这些方法的实现引导到子类或派生类。

现在我有 1 个问题:

  1. 在基类(抽象类)中实例化是否有用或常见?

或者,如果不是:

我们应该在派生类(子类)中进行实例化,还是在两者中都有?

哪个更好,或者说pythonic更好?

或者你可能会说没关系......如果是这样的话,请告诉我为什么。

例如,这个:

from abc import abstractmethod, ABC


class Athlete(ABC):
    def __init__(self, name: str,  mass: int, height: int, nationality: str):
        self.name = name
        self.mass = mass
        self.height = height
        self.nationality = nationality
    @abstractmethod
    def run(self):
        pass
    def play(self):
        pass
    def exercise(self):
        pass
    def sleep(self):
        pass


class SoccerPlayer(Athlete):
    def run(self):
        print(f"{self.name} is running")
    def play(self):
        print(f"{self.name} with {self.height} is running to save his {self.nationality} nation.")
    def exercise(self):
        print(f"{self.name} is exercising to fit his {self.mass}")
    def sleep(self):
        print(f"{self.name} is sleeping 8 h a day to increase his {self.height}m height.")


player = SoccerPlayer('ali', 200, 180, 'american')
player.run()

标签: pythonoopoverridingabstract-classabstract-methods

解决方案


对于测试,实例化一个抽象基类可能很方便。做起来也相当简单。但是,不要在生产代码中这样做。

你需要做的就是空的Athlete.__abstractmethods__

>>> Athlete("bob", 100, 200, "american")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Athlete with abstract methods run
>>> Athlete.__abstractmethods__
frozenset({'run'})
>>> Athlete.__abstractmethods__ = frozenset()
>>> Athlete("bob", 100, 200, "american")
<__main__.Athlete object at 0x10c9c0410>

推荐阅读