我寫了一個Python腳本,發現Python 3.4並沒有限制一個抽象類在Python 2.7.8中被實例化。我的抽象類Shape.py
。爲什麼我不受限於在Python 3.4中實例化抽象類?
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中的區域,但工作e在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 – jfs 2014-09-27 22:54:18