为什么不限制我在Python 3.4中实例化抽象类?
我编写了一个Python脚本,刚刚发现Python3.4并没有限制抽象类的实例化,而Python2.7.8限制了抽象类的实例化 这是我在名为为什么不限制我在Python 3.4中实例化抽象类?,python,abstraction,python-3.4,Python,Abstraction,Python 3.4,我编写了一个Python脚本,刚刚发现Python3.4并没有限制抽象类的实例化,而Python2.7.8限制了抽象类的实例化 这是我在名为Shape.py的文件中的抽象类 from abc import ABCMeta, abstractmethod class Shape: __metaclass__ = ABCMeta # Making the class abstract def __init__(self): pass: @abstrac
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
现在,我创建了另一个类,它继承了抽象
类形状
:文件名:
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
现在在myMain.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中,您以不同的方式声明元类:
class Shape(metaclass=ABCMeta):
见:
可以通过在类定义行中传递元类
关键字参数,或者通过从包含此类参数的现有类继承来定制类创建过程
for Python 3中的所有示例也使用正确的表示法
这是为了让元类有机会比Python2更早地参与类的创建;看
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
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
>>来自abc导入ABCMeta,abstractmethod
>>>类形状(元类=ABCMeta):
... @抽象方法
... def getArea(自):
... 打印(“你不应该打电话给我。”)
... 一无所获
...
>>>形状()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:无法使用抽象方法getArea实例化抽象类形状
谢谢。这起作用了。我真傻。你能不能也回答我的第三个子问题(编辑的问题)?提前感谢您的帮助。您可以使用six.add_meta_类decorator来支持Python 2和Python 3