Last active
September 24, 2015 03:56
-
-
Save AaronPhalen/36db32ddeec7b1348869 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Author: Aaron Phalen | Twitter: @aaron_phalen | Email: [email protected] | |
# Example of python class factory | |
# Dynamically create classes | |
Class1 = type("Class1", (), {"name": "class 1"}) | |
Class2 = type("Class2", (), {"name": "class 2"}) | |
# create factory class | |
class SampleClass(object): | |
"""class factory""" | |
@staticmethod | |
def factory(n): | |
"""factory method by integer name""" | |
n = int(n) | |
if n == 1: | |
instance = Class1() | |
elif n == 2: | |
instnace = Class2() | |
return instance | |
# access class factory instances | |
for instance in [SampleClass.factory(x) for x in xrange(1, 3)]: | |
print instance, instance.name | |
# Output | |
# <class '__main__.Class1'>, class 1 | |
# <class '__main__.Class2'>, class 2 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment