Skip to content

Instantly share code, notes, and snippets.

@nenetto
Last active September 26, 2023 06:40
Show Gist options
  • Save nenetto/ef7a14c96f66cac9a6837d5a8653a9d3 to your computer and use it in GitHub Desktop.
Save nenetto/ef7a14c96f66cac9a6837d5a8653a9d3 to your computer and use it in GitHub Desktop.
Example of classmethod for class polymorphism and different constructors
# Python only supports a single constructor per class, the __init__ method.
# Use @classmethod to define alternative constructors for your classes.
# Use class method polymorphism to provide generic ways to build and connect concrete subclasses.
class GenericInputData(object):
def read(self):
raise NotImplementedError
@classmethod
def generate_inputs(cls, config):
raise NotImplementedError
class PathInputData(GenericInputData):
def __init__(self, file_path):
self.file_path = file_path
def read(self):
return open(self.path).read()
@classmethod
def generate_inputs(cls, config):
"""Generators that create a PathInputData Object
for each file in config[‘data_dir’]
"""
data_dir = config[‘data_dir’]
for name in os.listdir(data_dir):
yield cls(os.path.join(data_dir, name)) # Generate a new object for each file in data_dir
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment