【问题标题】:Using isinstance() to check class variable's belonging使用 isinstance() 检查类变量的归属
【发布时间】:2015-12-26 17:33:53
【问题描述】:

我想使用 isinstance() 方法来识别类变量是否属于给定的类。

我创建了一个自己的 Enum() 基类来列出子类的类变量。 我没有详细说明源代码主体,不重要。

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']

我想用这个:

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

【问题讨论】:

  • Python 已经有了枚举,为什么要为此编写自己的类?
  • Python 3.4 有枚举。其他版本可以使用enum34的端口。
  • 这种貌似要重新实现一个字典。
  • 如果你不关心如何检查一个类是否有某个属性,这个问题可能对你有帮助:stackoverflow.com/questions/9748678/…
  • @jonrsharpe 不正确。可以用元类来完成,例如枚举的python实现就是这样设计的。

标签: python enums


【解决方案1】:

Enum 成为 Python 3.4 中的官方数据类型,there is a backport heredocs here

isinstance() 随心所欲地工作,并获取您将使用的成员的名称:

myEnum.__members__.keys()

虽然MyEnum['MyConstantA']MyEnum(0) 都会返回MyEnum.MyConstantA 成员。

【讨论】:

    【解决方案2】:

    看来普通的字典可以做你想做的:

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

    或者让enumerate 计算:

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

    然后:

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

    如果你真的想写自己的类,使用hasattr来测试类变量的存在:

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

    【讨论】:

    • 目标是实现isinstance()的使用。这个实现是更大结构的一部分,这就是为什么如果 isinstance() 可以以某种方式工作会很棒的原因。
    猜你喜欢
    • 2016-12-29
    • 1970-01-01
    • 2023-02-01
    • 2015-05-13
    • 2012-06-27
    • 2019-11-27
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多