簡體   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