繁体   English   中英

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

[英]Abstract class implementation not working in 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()是否不应该引发我Can't instantiate abstract class Base with abstract methods value的错误? 我究竟做错了什么? 我正在使用python 3.4

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

class Vehicle(metaclass=ABCMeta):

这是通过PEP 3115-Python 3000中的元类引入的


发生该问题的原因是,使用@abstractmethod装饰器时,要求该类的元类为ABCMeta或从其派生。 文档中所给-

@ abc.abstractmethod

装饰器,指示抽象方法。

使用此装饰器要求该类的元类为ABCMeta或从其派生。

(强调我的)

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM