0

I am trying to instantiate all the sublcasses of my abstract class that i have in my code, because the tagger function takes the same input. this is the code:

import spacy
nlp = spacy.load("en_core_web_sm")
from abc import ABC, abstractmethod

class SpacyTagger(ABC):
        
    @abstractmethod
    def tagger(self, texts):        
        pass

class SpacyTokenizer(SpacyTagger): 

    def tagger(Self,texts):
        for doc in nlp.pipe([texts]):
            return ([n.text for n in doc])
    
class SpacyLemmatizer(SpacyTagger):

    def tagger(self,texts):
        for doc in nlp.pipe([texts]):
            return ([n.lemma_ for n in doc])

of course, i can instantiate all subclasses separately like this:

token= SpacyTokenizer().tagger('she is a girl')    
lemma= SpacyLemmatizer().tagger('she is a girl')

but instead I would like to have it all in one line, or in a function that takes the text as the input. i also tried the function below to get all the subclasses' names, but do not know how to proceed from here, so i can just instantiate them once with the same input.

def all_subclasses(cls):
    return set(cls.__subclasses__()).union(
         [s for c in cls.__subclasses__() for s in all_subclasses(c)])
zara kolagar
  • 881
  • 3
  • 15
  • Are you sure you need instances? By using the @staticmethod decorator you can create static methods, which work without the need for an instance. – Pythocrates Jun 24 '21 at 14:44
  • thank you for your reply. I am actually new to oop, so i have not worked with @staticmethod before. could you please provide an example or a link i can look into?but i actually need an instance, and it might be a list of sentences. – zara kolagar Jun 24 '21 at 14:47
  • 1
    OK, you can try this: https://realpython.com/instance-class-and-static-methods-demystified/. But still: I see no need for instances in your code so far. And just instantiating all subclasses is a strange pattern. There should be no need for a class to track its subclasses. – Pythocrates Jun 24 '21 at 17:28

0 Answers0