Skip to content

Instantly share code, notes, and snippets.

@sea-shunned
Created March 6, 2019 13:17
Show Gist options
  • Save sea-shunned/b2e2fb0fba9f4720edb3a5d55cf0f155 to your computer and use it in GitHub Desktop.
Save sea-shunned/b2e2fb0fba9f4720edb3a5d55cf0f155 to your computer and use it in GitHub Desktop.
Alternative two-arg dict constructor method
import numpy as np
# Base class
class Base:
# Dict for creating instances with common data values
init_dict = {
'type_1': np.eye(3),
'type_2': np.random.random((4, 4))**0.5,
'type_3': np.linalg.inv(np.random.random((3, 3)))
}
# Two args to ensure differentiation
# Could add error checking if they're both None if you really want
# Put the more commonly used argument first if the keyword isn't provided
def __init__(self, default_type=None, value=None):
if default_type is not None:
try:
self.data = Base.init_dict[default_type]
except KeyError:
print(f"{default_type} is not a defined value in {Base.init_dict}")
raise
elif value is not None:
self.data = value
def some_method(self):
pass
def some_other_method(self):
pass
# Creating three common instances
v1 = Base('type_1')
v2 = Base('type_2')
v3 = Base('type_3')
# Creating another instance
v_other = Base(value=np.zeros((3, 3)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment