Home > OS >  How can I pass my dictonary into class with function?
How can I pass my dictonary into class with function?

Time:07-15

I want to declare a class using a dictionary and the ValueOrderedEnum library.

I have a dictionary

my_dict{'Blood':'4','Phlegm':'3','YellowBile':'2','BlackBile':'1'}

But I am totally clueless of how to set it as variables into this:

class Humor(ValueOrderedEnum):
   Blood = 4
   Phlegm = 3
   YellowBile = 2
   BlackBile = 1

CodePudding user response:

You can simply call ValueOrderedEnum with your dict as an argument to create the desired enumerated type.

>>> from ordered_enum import ValueOrderedEnum
>>> my_dict = {'Blood':'4','Phlegm':'3','YellowBile':'2','BlackBile':'1'}
>>> Humor = ValueOrderedEnum('Humor', my_dict)
>>> Humor.Blood > Humor.Phlegm
True
>>> Humor.Blood, Humor.Phlegm
(<Humor.Blood: '4'>, <Humor.Phlegm: '3'>)

Calling Enum (or a subclass thereof) is a way to programmatically do what inheriting from Enum (or its subclass) does declaratively. (Which is to say, classes with EnumMeta as their metaclass behave quite differently from classes with type as their metaclass.)

  • Related