Python 为什么继承没有';我不适合这个
1、 我首先使用了Python 2.7版,并通过pip安装了Python 为什么继承没有';我不适合这个,python,enums,Python,Enums,1、 我首先使用了Python 2.7版,并通过pip安装了enum模块 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(E
enum
模块
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')
这很好,但我想改进代码
2、 所以我想更好的方法可能是这样:
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')
但是,这会导致错误,因为BEnum.\uuuuu members\uuuuu
是一个类变量
我怎样才能让它工作呢?这里有三件事你需要做。首先,您需要使
BEnum
继承自Enum
:
class BEnum(Enum):
class Format(BEnum):
class Weather(BEnum):
接下来,您需要创建BEnum.exist
类方法:
@classmethod
def exist(cls,ele):
return cls.__members__.has_key(ele)
最后,您需要从BEnum
继承Format
和Weather
:
class BEnum(Enum):
class Format(BEnum):
class Weather(BEnum):
由于exist
是一个静态方法,它只能对特定类进行操作,而不管从哪个类调用它。通过使其成为类方法,调用它的类将自动作为第一个参数(cls
)传递,并可用于成员访问
是关于静态方法和类方法之间差异的一个很好的描述。对不起,我首先编写的代码有相同的错误,我已经修改了它。