【问题标题】:Is an abstract method a normal instance method in a non-abstract class in Python?抽象方法是Python中非抽象类中的普通实例方法吗?
【发布时间】:2022-11-22 02:40:41
【问题描述】:

我定义了抽象方法sound()@abstractmethod非抽象类Animal不扩展ABCCat班级延伸Animal班级,然后我可以实例化两者AnimalCat没有任何错误如下图:

from abc import ABC, abstractmethod

class Animal: # Doesn't extend "ABC"
    @abstractmethod # Here
    def sound(self):
        print("Wow!!")

class Cat(Animal):
    pass

obj1 = Animal() # Here
obj1.sound()

obj2 = Cat() # Here
obj2.sound()

输出:

Wow!!
Wow!!

所以,是抽象方法 一个普通的实例方法非抽象类在 Python 中?

【问题讨论】:

    标签: python python-3.x abstract-class abstract-methods instance-methods


    【解决方案1】:

    abstractmethod 装饰器只是向方法添加了一些注释,当您尝试实例化该类时,该方法由 ABC 评估。方法本身没有任何变化,它仍然是一个常规的实例方法。 ABC 与那些 abstractmethod 装饰器注释的合作导致了阻止“抽象类”实例化的预期行为。它不是以任何方式在语言级别强制执行的概念,它只是在常规 Python 类之上分层。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-16
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      相关资源
      最近更新 更多