Я написал скрипт Python и только что узнал, что Python 3.4 не ограничивает абстрактный экземпляр экземпляром, а Python 2.7.8.Почему я не ограничен созданием абстрактных классов в Python 3.4?
Вот мой абстрактный класс в файле с именем 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, но работает плавник 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