Skip to content

Instantly share code, notes, and snippets.

@coburnw
coburnw / MetaFactory.py
Last active October 2, 2023 06:00
Python Factory Using a Metaclass
# https://stackoverflow.com/a/5961102
# Note python3 has a different declaration than the so post
class ShapeFactory(type):
"""Shape Factory"""
def __call__(cls, selector, *args):
if cls is Shape:
# select a new object
print('factory build:', selector)
@coburnw
coburnw / NewFactory.py
Created October 2, 2023 01:31
Python Factory with __new__()
# https://stackoverflow.com/a/5961102
class Shape(object):
def __new__(cls, *args):
selector = args[0]
print('factory build:', selector)
if cls is Shape:
# Create a subclassed shape from a name
if selector == 'rectangle': return super(Shape, cls).__new__(Rectangle)
if selector == 'triangle': return super(Shape, cls).__new__(Triangle)