Skip to content

Instantly share code, notes, and snippets.

@coburnw
Created October 2, 2023 01:31
Show Gist options
  • Save coburnw/cba17dbdd0bd21e0a8ac9724d051b410 to your computer and use it in GitHub Desktop.
Save coburnw/cba17dbdd0bd21e0a8ac9724d051b410 to your computer and use it in GitHub Desktop.
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)
raise 'unrecognized shape'
else:
# a subclassed shape was created. return that one directly.
print('factory initialize:', selector)
return super(Shape, cls).__new__(cls)
def __init__(self, selector, junk):
"""Base Shape object. Contains factory and common methods
Args:
selector: The type of shape to build.
junk: The second parameter.
Returns:
Nothing.
"""
print("shape init")
self.desc = junk
self.edge_count = None
return
@property
def number_of_edges(self):
return self.edge_count
class Triangle(Shape):
def __init__(self, selector, junk):
print("triangle init")
super().__init__(selector, junk)
self.edge_count = 3
return
@property
def name(self):
return 'Triangle'
class Rectangle(Shape):
def __init__(self, selector, junk):
print("rectangle init")
super().__init__(selector, junk)
self.edge_count = 4
return
@property
def name(self):
return 'Rectangle'
if __name__ == '__main__':
shape = Shape('rectangle','big')
print('{} has {} edges'.format(shape.name, shape.number_of_edges))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment