-
Notifications
You must be signed in to change notification settings - Fork 0
Defining a Class
By subclassing the Obj
class and adding the right elements, you can still create very powerful enumerations without the need of the Enum Language.
The Obj
class is part of a class factory that will change its elements to work the expected way.
There is a set of defined functions that will yield a certain type of objects that will be translated in the right enumeration values and their attributes.
For the actual elements, either you add them in your class with integer values or you use the makeobj.keys
function to automatically create them for you (or with a generator function):
a = 1; b = 2; c = 3
a, b, c = keys(3)
a, b, c = keys(3, lambda x: 2*x + 1)
For attributes specific for each key, use the makeobj.attr
function with values for all of the keys or one only default argument and keyword arguments to specific keys:
val1 = attr('x', 'y', 'z')
val2 = attr('hey')
val3 = attr('default', a='other')
So MyEnum.b.val1 == 'y'
and MyEnum.c.val2 == 'hey'
and MyEnum.a.val3 == 'other'
Another option to add an attribute is to add it in the class directly. If this attribute is an int
object, it will be parsed as a value, so you'll need to use the class_attr
function. Other types do not share this problem, but it's better to keep safe by always using this function:
val = class_attr(10)
Now MyEnum.val == 10
as also MyEnum.a.val == 10
. Just make sure to not create a class attribute with the same name as a value.
Annotated example for defining an enumeration class and adding features:
from makeobj import Obj, keys, attr, class_attr
class ABCD(Obj):
a, b, c, d = keys(4) # The number 4 is needed for the
# tuple unpacking to work properly
w = attr('aa', 'bb', 'cc', 'dd') # A value for each key
x = attr(10) # Every key will receive the value 10
# for the name `x`
y = class_attr(10) # This attribute will be in the class
# not in each instance as the other one
z = attr(5, b=2) # Every one will receive 5 except from `b`
# which will receive 2