抽象类实现在python中不工作

2024-04-27 00:11:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用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()是否不应该抛出一个ICan't instantiate abstract class Base with abstract methods value的错误?我做错什么了?我使用的是python3.4


Tags: selfreturnmaindeftypesalepriceclass
2条回答

您使用的是Python2.x方法来定义metaclass,对于Python3.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.

(重点是我的)

U在Python2.x中使用的init方法中包含一个raise异常

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

这将不允许实例化抽象类。在

相关问题 更多 >