2014-09-27 103 views
4

我寫了一個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 

現在,我創建了另一個類,從abstractShape繼承:
文件名: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 
  1. 這究竟是爲什麼?這不是什麼抽象的!是嗎?
  2. 或者在Python 3.4中引入了抽象的新方法嗎?
  3. 任何一個可以給我的官方文檔的Python 3.4鏈接?
+0

你可以使用six.add_meta_class裝飾,同時支持Python的2 3 – jfs 2014-09-27 22:54:18

回答

8

在Python 3,你不同的聲明元類:

class Shape(metaclass=ABCMeta): 

Customizing class creation documentation

類創建過程可以通過將metaclass關鍵字參數在類定義定製行,或通過從包含這樣一個參數的現有類繼承。

Python 3的abc module documentation中的所有示例也使用正確的表示法。

這已被更改爲賦予元類更早參與類創建的機會,這比Python 2中的可能性要早;見PEP 3115

__metaclass__屬性不再具有特殊含義,所以您實際上並沒有創建適當的抽象類。

演示使用Python 3.4:

>>> from abc import ABCMeta, abstractmethod 
>>> class Shape(metaclass=ABCMeta): 
...  @abstractmethod 
...  def getArea(self): 
...   print("You shouldn't have called me.") 
...   return None 
... 
>>> Shape() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: Can't instantiate abstract class Shape with abstract methods getArea 
+0

謝謝。這工作。我多麼愚蠢。你能否回答我的第三個問題(編輯問題)?提前感謝您的幫助。 – 2014-09-27 17:32:44

+0

@Aditya:我已經爲你添加了文檔鏈接。 – 2014-09-27 17:33:14

+0

感謝您的文檔。 :) – 2014-09-28 16:48:49