Categories > Coding > Python >
Python abstraction abc plugin
Posted
I got some expertise writing in Java, however I am now compelled to develop in Python due to time constraints. What I'm attempting to do is create a class structure that extends from an abstract class Document down into numerous document kinds that, based on their type, would fetch different information from a database. Given that there are likely hundreds of distinct document kinds, I believe that utilising abstraction to offload as much functionality as possible further up the stack is my best option.
In Java, I would code something like this:
public abstract class Document(){
private String dept
private String date
...
public Document(){
...}
public abstract String writeDescription(){
...}
}
With Python, I'm not sure what my best choice is for doing anything like this. Right now, the two main options I've seen are to utilise the abc plugin.
https://docs.python.org/2/library/abc.html , Alternatively to utilise simple Python inheritance structures, such as this: Abstraction in Python?
Is it possible to complete my task without using the ABC plugin, or would it be necessary?
Thank you
Replied
just create a class with an abstract method and any class that extends it needs to implement that method or it will throw an error
class Document:
def __init__(self, dept, date):
self.dept = dept
self.date = date
def write_description(self):
raise NotImplementedError("subclass must implement abstract method")
class Invoice(Document):
def write_description(self):
return f"Invoice {self.date} for {self.dept}"
Cancel
Post
A Quick One Before the Eternal Worm Devours Connecticut
Users viewing this thread:
( Members: 0, Guests: 1, Total: 1 )
Cancel
Post