简体   繁体   中英

Abstract class implementation not working in python

I am trying to implement an abstract class in 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 ? What am I doing wrong? I am using python 3.4

You are using the Python 2.x method of defining metaclass , For Python 3.x you need to do the following -

class Vehicle(metaclass=ABCMeta):

This was introduced through PEP 3115 - Metaclasses in 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. As given in 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.

(Emphasis mine)

U include a raise exception in init method to use in Python2.x

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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