DJ M
DJ M

Reputation: 41

Python Classes Within a Class

I am working on a project in which I am adding to someones already extensive code. The project is quite involved but the basics is that there are a number of files that need to be parsed (each with different parsers depending on what the file contains) and all I am doing is adding a new parser to the preexisting ones.

The only issue is that I have already spent many hours writing my parser as a standalone program and as such have designed it in a way that is not consistent with the original author's methods (for example, each of his parsers is a subclass of Parser() and inherit a few things).

The main difference between my parser and his are that each of his parsers are simply one class (xParser, yParser, etc.) that handle all of the parsing, while my parser as it stands uses one of two classes depending on the format of the input.

My question is, would it be okay for me to just wrap these two classes under one outer class and have them exist as classes within a class? Otherwise I would have to either change my code drastically or change the entire project. I know that this is certainly not an ideal way to go about things and I may be able to change it in the future but is this an acceptable solution for the short term?

Thanks!

Upvotes: 0

Views: 1780

Answers (2)

cephalopodMD
cephalopodMD

Reputation: 169

An easier solution would be that as long as the input and output are roughly the same for the two, you could just write a dummy class that inherits from Parser. This dummy class would have an instance of your independent class, and call your class' methods in the inherited Parser methods that you over ride.

pseudocode:

class ParserZZ(Parser):
    def __init__(self, whatever):
        self.myparser = MyParser(whatever)

    def parse(self, foo):
        return self.myparser.parse(foo)

You can easily refactor this as needed and it will intereact with the existing codebase better. The only major concern is that this will spaghettify your code. I would seriously look into just redoing the class completely maybe copying a little from your independent class here or there. I promise it wont be as bad as you think it will, and it will save you future headaches.

Upvotes: 1

OJFord
OJFord

Reputation: 11140

If the only question is "does it work?" - why not just try it:

>>> class a:
...     class b:
...         def c(self):
...             print('d')
... 
>>> a().b().c()
d

Yes, it does work, if all you need(/want) here is some quick and dirty solution.

Upvotes: 0

Related Questions