简体   繁体   English

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

[英]Abstract class implementation not working in python

I am trying to implement an abstract class in python. 我正在尝试在python中实现一个抽象类。 Following is my code: 以下是我的代码:

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()

This executes perfectly without giving any error. 这将完美执行而不会出现任何错误。 Is the main() not supposed to throw an error that I Can't instantiate abstract class Base with abstract methods value ? main()是否不应该引发我Can't instantiate abstract class Base with abstract methods value的错误? What am I doing wrong? 我究竟做错了什么? I am using python 3.4 我正在使用python 3.4

You are using the Python 2.x method of defining metaclass , For Python 3.x you need to do the following - 您正在使用定义metaclass的Python 2.x方法,对于Python 3.x,您需要执行以下操作-

class Vehicle(metaclass=ABCMeta):

This was introduced through PEP 3115 - Metaclasses in Python 3000 这是通过PEP 3115-Python 3000中的元类引入的


The issue occurs because for using @abstractmethod decorator it is required that the class's metaclass be ABCMeta or be derived from it. 发生该问题的原因是,使用@abstractmethod装饰器时,要求该类的元类为ABCMeta或从其派生。 As given in the documentation - 文档中所给-

@abc.abstractmethod @ abc.abstractmethod

A decorator indicating abstract methods. 装饰器,指示抽象方法。

Using this decorator requires that the class's metaclass is ABCMeta or is derived from it. 使用此装饰器要求该类的元类为ABCMeta或从其派生。

(Emphasis mine) (强调我的)

U include a raise exception in init method to use in Python2.x U在Python2.x中使用的init方法中包含一个引发异常

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

This will not allow the abstract class to be instantiated. 这将不允许实例化抽象类。

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

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