我正在尝试在 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() 是否不应抛出“我无法使用抽象方法值实例化抽象类 Base”的错误?我究竟做错了什么?我正在使用 python 3.4
最佳答案
您正在使用 Python 2.x 定义元类的方法,对于 Python 3.x,您需要执行以下操作 -
class Vehicle(metaclass=ABCMeta):
这是通过 PEP 3115 - Metaclasses in Python 3000 引入的
出现此问题是因为使用 @abstractmethod
装饰器需要类的元类为 ABCMeta 或从其派生。如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.
(强调我的)
关于python - 抽象类实现在 python 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32731604/