简体   繁体   English

使用isinstance()检查类变量的归属

[英]Using isinstance() to check class variable's belonging

I would like to use isinstance() method to identify class variable is it belongs to the given class. 我想使用isinstance()方法来识别类变量,因为它属于给定的类。

I created an own Enum() base class to list class variables of subclasses. 我创建了一个自己的Enum()基类以列出子类的类变量。 I did't detail body of source code, not important. 我没有详细说明源代码的主体,并不重要。

class Enum(object):

    @classmethod
    def keys(cls):
        pass  # Returns all names of class varables.

    @classmethod
    def values(cls):
        pass  # Returns all values of class varables

    @classmethod
    def items(cls):
        pass # Returns all class variable and its value pairs.

class MyEnum(Enum):
    MyConstantA = 0
    MyConstantB = 1

>>>MyEnum.keys()
['MyConstantA', 'MyConstantB']

I would like to use this one: 我想使用这个:

>>>isinstance(MyEnum.MyConstantB, MyEnum)
True

Enum became an official data type in Python 3.4, and there is a backport here , with docs here . Enum在Python 3.4中成为官方数据类型,并且这里有一个backport,这里是 docs

isinstance() works as you would like, and to get the names of the members you would use: isinstance()可以根据需要工作,并且可以使用以下成员的名称:

myEnum.__members__.keys()

While both MyEnum['MyConstantA'] and MyEnum(0) would return the MyEnum.MyConstantA member. 虽然MyEnum['MyConstantA']MyEnum(0)都将返回MyEnum.MyConstantA成员。

It seems that an ordinary dictionary can do what you want: 普通字典似乎可以满足您的要求:

>>> myEnum = {'MyConstantA': 0, 'MyConstantB': 1}

Or let enumerate do the counting: 或者让我们enumerate计数:

>>> myEnum = {k: i for i, k in enumerate(['MyConstantA', 'MyConstantB'])}

Then: 然后:

>>> myEnum.keys()
['MyConstantA', 'MyConstantB']
>>> myEnum.values()
[0, 1]
>>> myEnum.items()
[('MyConstantA', 0), ('MyConstantB', 1)]
>>> 'MyConstantB' in myEnum
True

In case you really want to write your own class, use hasattr to test the existence of class variables: 如果您确实想编写自己的类,请使用hasattr测试类变量的存在:

>>> class Foo:
...     bar = 5
...
>>> hasattr(Foo, 'bar')
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM