TypeError: 无法实例化抽象类。为什么?

huangapple go评论69阅读模式
英文:

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')

huangapple
  • 本文由 发表于 2023年5月28日 16:10:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76350533.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定