>類和abc
> Decorator。 ABC
abstractmethod
>模塊中導入ABC
> class和Decorator:abstractmethod
>abc
from abc import ABC, abstractmethod
ABC
@abstractmethod
>繼承來定義抽像類。 然後,您使用
>裝飾器聲明抽象方法。 抽象方法沒有身體;他們僅聲明方法簽名。from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass
這是一個示例:在此示例中,在此示例中,Shape
是一個抽像類,帶有兩個抽象方法:area
和perimeter
。 Attempting to instantiate Shape
directly will raise a TypeError
.
Abstract classes offer several key advantages:
TypeError
@abstractmethod
TypeError
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14159 * self.radius * self.radius # Missing perimeter method! class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height def perimeter(self): return 2 * (self.width + self.height) # This will raise a TypeError # circle = Circle(5) rectangle = Rectangle(4, 5) print(rectangle.area()) # Output: 20 print(rectangle.perimeter()) # Output: 18
i在使用pyty py in ot py <> <<< <<在子類中執行方法實現。 如果子類未實現其父級抽像類中定義的所有抽象方法,則試圖實例化子類將引起Circle
>。 area
TypeError
>讓我們擴展上一個示例:Rectangle
中創建接口,而Python沒有以與Java或C#相同的方式具有顯式接口,而是有效地實現了接口的目的。 一個只有抽象方法的抽像類充當接口,定義具體類必須遵守的合同。
>這意味著您可以使用抽像類指定任何實現類都必須提供的一組方法,而無需指定任何實現詳細信息。 這促進了鬆散的耦合和更好的設計原理。 區別是微妙的; Python's approach emphasizes implementation inheritance along with interface definition, while languages with explicit interfaces often decouple them.
For example, if you only needed the method signatures without any implementation in Shape
, you'd still use an abstract class, effectively creating an interface:
from abc import ABC, abstractmethod
This ShapeInterface
acts like an interface;它沒有提供任何實現細節,僅提供希望符合“形狀”概念的類所需的方法。
以上是如何在Python中實現抽像類?的詳細內容。更多資訊請關注PHP中文網其他相關文章!