据我目前的理解(请注意我的话中定义的正确性):我们应该在抽象类中声明我们的抽象方法,并将这些方法的实现引导到子类或派生类中。
现在我有 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()
最佳答案
对于测试,实例化抽象基类可能会很方便。做起来也相当简单。不过,不要在生产代码中执行此操作。
您需要做的就是清空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>
关于python - 对于抽象类来说,实例化的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59335079/