本文介绍了带有属性的python枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

考虑:

类项目:def __init__(self, a, b):self.a = a自我.b = b类项目:绿色 = 项目('a','b')蓝色 = 项目('c', 'd')

有没有办法使简单枚举的想法适应这种情况?(参见这个问题)理想情况下,如在 Java 中,我想把它全部塞进一个类中.

Java 模型:

enum EnumWithAttrs {绿色(a",b"),蓝色(c",d");EnumWithAttrs(String a, String b) {this.a = a;this.b = b;}私人字符串a;私人字符串 b;/* 访问器和其他 Java 噪声 */}
解决方案

Python 3.4 有一个 新的枚举数据类型(已被反向移植为enum34增强为 aenum).enum34aenum 都可以轻松支持您的用例:

[aenum py2/3]

导入枚举类 EnumWithAttrs(aenum.AutoNumberEnum):_init_ = 'a b'绿色 = 'a', 'b'蓝色 = 'c', 'd'

[enum34 py2/3 或 stdlib enum 3.4+]

导入枚举类 EnumWithAttrs(enum.Enum):def __new__(cls, *args, **kwds):值 = len(cls.__members__) + 1obj = object.__new__(cls)obj._value_ = 值返回对象def __init__(self, a, b):self.a = a自我.b = b绿色 = 'a', 'b'蓝色 = 'c', 'd'

并在使用中:

-->EnumWithAttrs.BLUE<EnumWithAttrs.BLUE: 1>-->EnumWithAttrs.BLUE.a'C'

披露:我是 Python stdlib 的作者Enumenum34 向后移植a> 和 高级枚举 (aenum) 库.>

aenum 还支持 NamedConstants 和基于元类的 NamedTuples.

Consider:

class Item:
   def __init__(self, a, b):
       self.a = a
       self.b = b

class Items:
    GREEN = Item('a', 'b')
    BLUE = Item('c', 'd')

Is there a way to adapt the ideas for simple enums to this case? (see this question) Ideally, as in Java, I would like to cram it all into one class.

Java model:

enum EnumWithAttrs {
    GREEN("a", "b"),
    BLUE("c", "d");

    EnumWithAttrs(String a, String b) {
      this.a = a;
      this.b = b;
    }

    private String a;
    private String b;

    /* accessors and other java noise */
}
解决方案

Python 3.4 has a new Enum data type (which has been backported as enum34 and enhanced as aenum). Both enum34 and aenum easily support your use case:

[aenum py2/3]

import aenum
class EnumWithAttrs(aenum.AutoNumberEnum):
    _init_ = 'a b'
    GREEN = 'a', 'b'
    BLUE = 'c', 'd'

[enum34 py2/3 or stdlib enum 3.4+]

import enum
class EnumWithAttrs(enum.Enum):

    def __new__(cls, *args, **kwds):
        value = len(cls.__members__) + 1
        obj = object.__new__(cls)
        obj._value_ = value
        return obj

    def __init__(self, a, b):
        self.a = a
        self.b = b

    GREEN = 'a', 'b'
    BLUE = 'c', 'd'

And in use:

--> EnumWithAttrs.BLUE
<EnumWithAttrs.BLUE: 1>

--> EnumWithAttrs.BLUE.a
'c'


Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

aenum also supports NamedConstants and metaclass-based NamedTuples.

这篇关于带有属性的python枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 15:37