python - 抽象类实现在 python 中不起作用

标签 python python-3.x abstract-class

我正在尝试在 python 中实现一个抽象类。以下是我的代码:

from abc import ABCMeta, abstractmethod

class Vehicle:
    __metaclass__ = ABCMeta

    def __init__(self, miles):
        self.miles = miles        

    def sale_price(self):
        """Return the sale price for this vehicle as a float amount."""
        if self.miles > 10000:
            return 20.0  
        return 5000.0 / self.miles

    @abstractmethod
    def vehicle_type(self):
        """"Return a string representing the type of vehicle this is."""
        pass

class Car(Vehicle):
    def vehicle_type(self):
        return 'car'

def main():
    veh = Vehicle(10)
    print(veh.sale_price())
    print(veh.vehicle_type())

if __name__ == '__main__':
    main()

这可以完美执行,不会出现任何错误。 main() 是否不应抛出“我无法使用抽象方法值实例化抽象类 Base”的错误?我究竟做错了什么?我正在使用 python 3.4

最佳答案

您正在使用 Python 2.x 定义元类的方法,对于 Python 3.x,您需要执行以下操作 -

class Vehicle(metaclass=ABCMeta):

这是通过 PEP 3115 - Metaclasses in Python 3000 引入的


出现此问题是因为使用 @abstractmethod 装饰器需要类的元类为 ABCMeta 或从其派生。如the documentation -中给出的

@abc.abstractmethod

A decorator indicating abstract methods.

Using this decorator requires that the class’s metaclass is ABCMeta or is derived from it.

(强调我的)

关于python - 抽象类实现在 python 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32731604/

相关文章:

python - 在类 __init__ 中使用 Argparse

python-3.x - OpenCV - Python 将底部添加到现有图像

python-3.x - 如何将表情符号嵌入到 Tweepy 状态文本中?

python - 使用抽象方法进行 Pycharm 类型提示

python - 处理分类中稀有因子水平的一般策略?

python - 为具有相同扩展名的多个文件运行脚本。获取 'UnboundLocalError'

python - 如何在 GNU/Linux 中使用 python 自动化 GUI 应用程序的操作?

python - 有没有办法不计算不必要的金额来节省时间?

java - 抽象类的具体子类作为原始类中的参数,没有抽象方法实现

java - 从另一个抽象类扩展的抽象类的重要性是什么