Categories > Coding > Python >

Python abstraction abc plugin

Posts: 13

Threads: 8

Joined: Mar, 2023

Reputation: 0

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?

  • 0

Thank you

Lunox

Mole

vip

Posts: 58

Threads: 6

Joined: Jun, 2022

Reputation: 31

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}"
  • 0

A Quick One Before the Eternal Worm Devours Connecticut

Users viewing this thread:

( Members: 0, Guests: 1, Total: 1 )