英文:
TypeError: Can't instantiate abstract class. Why?
问题
为什么Python会报错,提示'TypeError: 无法实例化抽象类Person,因为它具有抽象方法introduce_yourself'?
from abc import ABC, abstractmethod
class Person(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def introduce_yourself(self):
pass
adam = Person('Adam')
英文:
Why is python writing me this error 'TypeError: Can't instantiate abstract class Person with abstract method introduce_yourself'?
from abc import ABC, abstractmethod
class Person(ABC):
def __init__(self, name) -> None:
self.name=name
@abstractmethod
def introduce_yourself(self):
pass
adam = Person('Adam')
答案1
得分: 1
你遇到的错误是因为你试图创建一个Person类的实例,而该类被定义为一个抽象类。抽象类不能直接实例化,也就是说你不能创建抽象类的对象。子类必须实现抽象类中定义的任何抽象方法。
示例
from abc import ABC, abstractmethod
class Person(ABC):
def __init__(self, name) -> None:
self.name=name
@abstractmethod
def introduce_yourself(self):
pass
class SubPerson(Person):
def introduce_yourself(self):
print("myself")
adam = SubPerson('Adam')
英文:
The error you are encountering is occurring because you are trying to create an instance of the Person class, which is defined as an abstract class. Abstract classes cannot be instantiated directly, meaning you cannot create objects of abstract classes. Subclasses must implement any abstract methods defined in the abstract class.
Example
from abc import ABC, abstractmethod
class Person(ABC):
def __init__(self, name) -> None:
self.name=name
@abstractmethod
def introduce_yourself(self):
pass
class SubPerson(Person):
def introduce_yourself(self):
print("myself")
adam = SubPerson('Adam')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论