我试图用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()是否不应该抛出一个ICan't instantiate abstract class Base with abstract methods value
的错误?我做错什么了?我使用的是python3.4
您使用的是Python2.x方法来定义
metaclass
,对于Python3.x,您需要执行以下操作-这是通过PEP 3115 - Metaclasses in Python 3000引入的
发生此问题是因为要使用
@abstractmethod
修饰符,类的元类必须是ABCMeta或从它派生。如the documentation -(重点是我的)
U在Python2.x中使用的init方法中包含一个raise异常
这将不允许实例化抽象类。在
相关问题 更多 >
编程相关推荐