1

I made a function ClassAttribsToDict which would convert user-defined attributes in a class to dictionary.

def ClassAttribsToDict(myclass):
  return dict(filter(lambda (k,v): not k.startswith("__"),vars(myclass).items()))

class AnimalEnums(object):
  dog = 0
  cat = 2
  horse = 7

Executing the function on a class name converts it into dictionary

>>> ClassAttribsToDict(AnimalEnums)
{'horse': 7, 'dog': 0, 'cat': 2}

Now I tried to make a base class and include this method ClassAttribsToDict as a classmethod:

class EnumBase(object):
  @classmethod
  def ClassAttribsToDict(myclass):
    return dict(filter(lambda (k,v): not k.startswith("__"),vars(myclass).items()))

However when I try to call ClassAttribsToDict function on class EnumBase, I get following error:

>>> EnumBase.ClassAttribsToDict(AnimalEnums)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ClassAttribsToDict() takes exactly 1 argument (2 given)

Further, I want to inherit EnumBase class to make them behave as enumeration as follows:

class LanguagesEnum(EnumBase):
  EN = 0
  CN = 1
  FR = 2
  DE = 3

And expect to convert class attributes to dictionary

>>> LanguagesEnum.ClassAttribsToDict(LanguagesEnum)
nurabha
  • 1,152
  • 3
  • 18
  • 42

1 Answers1

2

Effectively, by adding @classmethod you're making your def ClassAttribsToDict's first parameter always be the class it's included in (which would be EnumBase in this case). It's similar to how your "regular" methods in class always takes starts with self, except it takes the class itself instead of a class instance.

So when you're calling EnumBase.ClassAttribsToDict(AnimalEnums), it's actually acting like ClassAttribsToDict(EnumBase, AnimalEnums), from the method's perspective (thus it thinks it's got 2 arguments).

anyway : changing to def ClassAttribsToDict(cls, myclass): will very likely work out for you.

(Also a side note - according to PEP8 you should probably switch to class_attribs_to_dict for methods, classes can stay CapsWords style)

bmjeon5957
  • 291
  • 1
  • 10