• 已解决 73482 个问题
  • 已帮助 5993 位优秀工程师

python中怎么实现typedef enum的枚举功能

勇哥来巡山 2018-09-20 浏览量:901
python中怎么实现typedef enum的枚举功能
0 0 收起

我来回答

上传资料:
选择文件 文件大小不超过15M(格式支持:doc、ppt、xls、pdf、zip、rar、txt)
最佳答案
  • 你需要枚举那些功能特性?

    常量数值定义? 这个python没有定义常量的直接机制,一般是用大写字母变量标志常量的,也可以定义

    # -*- coding: utf-8 -*-
    # filename: const.py
     class _const: class ConstError(TypeError) : pass def __setattr__(self key value): # self.__dict__ if self.__dict__.has_key(key): raise self.ConstError"constant reassignment error!" self.__dict__[key] = value import sys sys.modules[__name__] = _const()

    import const
    const.package_max_size = 10000
    实现
    常量只能定义一次的效果

    而枚举另外一个功能是限制变量的取值,这个python也没有直接的机制,你也只能通过其他如取值检测等符合要求再赋值等方式实现类似效果,或者在编程中直接注意(人工)

    • 发布于 2018-09-21
    • 举报
    • 评论 1
    • 0
    • 0
xdsnet 回复了 xdsnet:从python3.4开始,有一个enum模块,可以支持定义枚举,它也方便了枚举赋值检测,不过本质对赋值这样的特性要求也是不支持的。 回复

其他答案 数量:5
  • 1.我们通常将一组常用的常数定义在一个class中,每个常量就是class的一个实例;
    2.当一个变量有几种可能的取值的时候,我们将它定义为枚举类型。

    例如

    from enum import Enum

    class Animals(Enum):

        ant = 1
        bee = 2
        cat = 3
        dog = 4
    • 发布于2018-09-21
    • 举报
    • 评论 0
    • 0
    • 0

  • 一个简单的枚举实现方法
    class Enumerate(object):
      def __init__(selfnames):
        for numbername in enumerate(names.split()):
          setattr(self name number)
    codes = Enumerate('FOO BAR BAZ')
    print codes.FOO
    codes.FOO = 10
    print codes.FOO

    • 发布于2018-09-21
    • 举报
    • 评论 0
    • 0
    • 0

  • 参考这个https://www.cnblogs.com/yanglang/p/7428738.html
    • 发布于2018-09-26
    • 举报
    • 评论 0
    • 0
    • 0

  • python中只有类和方法,enum也只能是新建一个类来实现,即使用class关键字新建一个只有int型变量的类​。

    • 发布于2018-09-27
    • 举报
    • 评论 0
    • 0
    • 0

相关问题

问题达人换一批

python中怎么实现typedef enum的枚举功能