【问题标题】:What is the best way for instantiation in the case of abstract classes?在抽象类的情况下,实例化的最佳方式是什么?
【发布时间】:2020-04-07 15:28:31
【问题描述】:

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

现在我有 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()

【问题讨论】:

  • 抽象基类的全部意义在于您不要实例化它。
  • @user10987432,所以我应该在子类中进行实例化....对吗?

标签: python oop overriding abstract-class abstract-methods


【解决方案1】:

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

您只需清空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>

【讨论】:

    【解决方案2】:

    总是为派生类做实例化。

    因为如果你在基类中进行实例化,你将继承派生类中的那些属性和方法,但也要考虑到这一点,你可能想要覆盖你在基类中实例化的属性(抽象班级)。在那个时候,您需要快速修改抽象类中的属性,这不是一个好主意。

    所以在子类而不是抽象类中实例化你的属性。

    【讨论】:

      猜你喜欢
      • 2022-07-22
      • 1970-01-01
      • 2023-03-18
      • 2012-05-04
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      相关资源
      最近更新 更多