gpt4 book ai didi

python - TypeError : Can't instantiate abstract class <. ..> 使用抽象方法

转载 作者:行者123 更新时间:2023-12-05 04:09:12 28 4
gpt4 key购买 nike

这是我的代码:

from abc import ABC
from abc import abstractmethod

class Mamifiero(ABC):
"""docstring for Mamifiero"""
def __init__(self):
self.alimentacion = 'carnivoro'

@abstractmethod
def __respirar(self):
print('inhalar... exhalar')

class Perro(Mamifiero):
"""docstring for Perro"""
def __init__(self, ojos=2,):
self.ojos = ojos

我想要 perro.respirar() 打印 'inhalar... exhalar' 但是当我想实例化一个 Perro 类时显示这个错误。我想知道我的脚本有什么问题

最佳答案

根据定义(阅读文档),抽象调用是一个类,在它有任何未被覆盖的抽象方法之前不能被实例化。就像在面向对象编程设计中一样。

您有一个抽象方法 Perro.__respirar() 没有被覆盖,因为它是从父类继承的。或者,用 Perro.__respirar() 方法覆盖它,并在那里做一些事情(甚至可以调用父方法;当然,如果它是带有双下划线的 private 则不行)。

如果你想实例化Perro,只是不要让那个方法抽象。让它正常。因为它也有一些实现,这表明它是一个普通的基类方法,而不是抽象方法。

关于python - TypeError : Can't instantiate abstract class <. ..> 使用抽象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46505037/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com