[英]How to define a method in class that inherits from Abstract Base Class
I have two abstract Classes with two methods: getArea(width, height)
and getPerimeter(width, height)
.我有两个带有两种方法的抽象类:
getArea(width, height)
和getPerimeter(width, height)
。 Those methods are abstract too, so they can be (or not) implemented in a derived class (In my case they must be implemented).这些方法也是抽象的,因此它们可以(或不)在派生类中实现(在我的情况下,它们必须实现)。 In C# I could write
IRectangle.getArea(){}
or IParallelogram.getPerimeter(){}
and simply make implementation.在 C# 中,我可以编写
IRectangle.getArea(){}
或IParallelogram.getPerimeter(){}
并简单地进行实现。 How can I do this in Python?我怎样才能在 Python 中做到这一点? I think that I have to use something like
super(IRectangle, self).getArea()
but I am not sure how.我认为我必须使用像
super(IRectangle, self).getArea()
这样的东西super(IRectangle, self).getArea()
但我不确定如何使用。
from abc import ABC, abstractmethod
class IRectangle(ABC):
@abstractmethod
def getArea(width, height):
pass
@abstractmethod
def getPerimeter(width, height):
pass
class IParallelogram(ABC):
@abstractmethod
def getArea(parHeight, parBase):
pass
@abstractmethod
def getPerimeter(parHeight, parBase):
pass
class Calculate (IParallelogram, IRectangle):
You would just make a class that inherits from the abstract class and overrides the abstract methods like you would write a regular method.您只需创建一个继承自抽象类并覆盖抽象方法的类,就像编写常规方法一样。
class A(ABC):
@abstractmethod
def f(self):
pass
class B(A):
def f(self):
print ('hello')
If you want to override it but make it do nothing:如果你想覆盖它但让它什么都不做:
class B(A):
def f(self):
pass
Your class hierarchy is upside down.您的类层次结构是颠倒的。 First, you would define a more generic class like
Shape
as the (abstract) root of the hierarchy.首先,您将定义一个更通用的类,如
Shape
作为层次结构的(抽象)根。
class Shape(ABC):
@abstractmethod
def getArea(self):
pass
@abstractmethod
def getPerimeter(self):
pass
Then, the concrete classes IRectangle
and IParallelogram
would implement getArea
and getPerimeter
appropriately.然后,具体的类
IRectangle
和IParallelogram
将适当地实现getArea
和getPerimeter
。
class IRectangle(Shape):
def getArea(self):
...
def getPerimeter(self):
...
class IParallelogram:
def getArea(self):
...
def getPerimeter(self):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.