nven nven - 2 months ago 5x
Python Question

Add new functions to a class with import

I have a class which has the function of parsing data.

class DataContainer(object):
def parser1(data):
# Handle data in one way
self.parsed_data = parsed_data

def parser2(data):
# Handle data another way
self.parsed_data = parsed_data

The parser functions popular the instance variables of the class. This parser may be changed or have many variations, so I would like to import another file with the functions, something like this:

class DataContainer(object):
import parsers # Contains all the parsing functions which can then be called from instances

Is there a particular 'pythonic' way to do this?


It depends on exactly how you want to use your object, but I would import parsers, and then have your DataContainer serve as an interface to those functions

import parsers

class DataContainer(object):

    def __init__(self):
        # If this kind of thing is needed for the library
        self.parsers = parsers.Parser() 

    def parser1(self,data):
        # prep data however you need
        parsed_data = self.parsers.parse_method1(prep_data)
        # set instance variables from parsed_data