抽象类实现在python中不起作用
我试图用python实现一个抽象类。以下是我的代码:抽象类实现在python中不起作用,python,python-3.x,abstract-class,Python,Python 3.x,Abstract Class,我试图用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 veh
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()是否不应该抛出一个错误,即I
无法使用抽象方法值实例化抽象类基?我做错了什么?我使用的是Python3.4您使用的是定义元类的Python2.x方法,对于Python3.x,您需要执行以下操作-
class Vehicle(metaclass=ABCMeta):
这是通过
出现此问题的原因是,要使用@abstractmethod
装饰器,需要类的元类为ABCMeta或从中派生。如
@abc.abstractmethod
表示抽象方法的装饰器
使用此修饰符需要类的元类是ABCMeta或派生自ABCMeta。
(Emphasis mine)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
这将不允许实例化抽象类。在Python 3中,元类不是这样定义的。@AshwiniChaudhary您能告诉我正确的方法吗?非常有效。我将在6分钟内接受答案(只要SO允许)。谢谢