sungs
sungs

Reputation: 33

why inheritance doesn't work well for this

1、I first used Python version 2.7, and through pip installed enum module.

from enum import Enum

class Format(Enum):
    json = 0
    other = 1
    @staticmethod
    def exist(ele):
        if Format.__members__.has_key(ele):
            return True
        return False

class Weather(Enum):
    good = 0
    bad = 1
    @staticmethod
    def exist(ele):
        if Weather.__members__.has_key(ele):
            return True
        return False

Format.exist('json')

Which works well, but I want to improve the code.

2、So I thought a better way might be like this:

from enum import Enum

class BEnum(Enum):
    @staticmethod
    def exist(ele):
        if BEnum.__members__.has_key(ele)                   
            return True
        return False

class Format(Enum):
    json = 0
    other = 1

class Weather(Enum):
    good = 0
    bad = 1

Format.exist('json')

However this results in an error, because BEnum.__members__ is a class variable.

How can I get this to work?

Upvotes: 1

Views: 75

Answers (1)

user2508324
user2508324

Reputation:

There are three things you need to do here. First, you need to make BEnum inherit from Enum:

class BEnum(Enum):

Next, you need to make BEnum.exist a class method:

    @classmethod
    def exist(cls,ele):
        return cls.__members__.has_key(ele)

Finally, you need to have Format and Weather inherit from BEnum:

class Format(BEnum):

class Weather(BEnum):

With exist being a static method, it can only operate on a specific class, regardless of the class that it is called from. By making it a class method, the class it is called from is passed automatically as the first argument (cls), and can be used for member access.

Here is a great description about the differences between static and class methods.

Upvotes: 3

Related Questions