摘要 class 实现在 python 中不起作用

Abstract class implementation not working in python

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

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() 不应该抛出我 Can't instantiate abstract class Base with abstract methods value 的错误吗?我究竟做错了什么?我正在使用 python 3.4

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

class Vehicle(metaclass=ABCMeta):

这是通过 PEP 3115 - Metaclasses in Python 3000

介绍的

出现这个问题是因为使用 @abstractmethod 装饰器需要 class 的元 class 是 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.

(强调我的)

U 在 init 方法中包含引发异常以在 Python2.x

中使用
class Vehicle:
   __metaclass__=abc.ABCMeta
   def __init__(self):
      raise NotImplemetedError('The class cannot be instantiated')
   @abstractmethod
   def vehicletype(self):
       pass

这将不允许实例化抽象 class。