【发布时间】:2014-09-27 17:25:31
【问题描述】:
我编写了一个 Python 脚本,发现 Python 3.4 并没有限制抽象类被实例化,而 Python 2.7.8 可以。
这是我在名为Shape.py 的文件中的抽象类。
from abc import ABCMeta, abstractmethod
class Shape:
__metaclass__ = ABCMeta # Making the class abstract
def __init__(self):
pass:
@abstractmethod
def getArea(self):
print("You shouldn't have called me.")
return None
现在我创建了另一个继承自 abstract 类 Shape 的类:
文件名:Circle.py
from Shape import Shape
class Circle(Shape):
PI = 3.141
def __init__(self, radius=0):
self.radius = radius
def getArea(self): # Overriding it from Shape class
return self.PI * self.radius ** 2
现在在我的Main.py:
from Shape import Shape
from Circle import Circle
shape = Shape() # This gave me errors in Python 2.7.8 but not in Python 3.4
shape2 = Circle(5)
print("Area of shape = "+str(shape.getArea())) # This should have not been executed.
print("Area of circle = "+str(shape2.getArea()))
这个Main.py 在 Python2.7.8 中的注释区域出现错误,但在 Python3.4 上运行良好。
Python3.4 上的输出:
You shouldn't have called me
Area of shape = None
Area of circle = 78.525
- 为什么会这样?这不是抽象!是吗?
- 或者是否在 Python 3.4 中引入了任何新的抽象方法?
- 谁能给我python 3.4官方文档的链接?
【问题讨论】:
-
你可以使用 Six.add_meta_class 装饰器来支持 Python 2 & 3
标签: python abstraction python-3.4