`

Use of Python metaclass II - Python Enumeration

阅读更多

In my previous post, I disussesed with the reader the concept of metaclass and its internals. and in following post one usage of the python metaclass is discussed. Today another use of the metaclass will be discussed.

 

As a note, this article is inspired from this original post from stackoverflow.

 

Problem with Python and Enumeration

python does not have internal keyword for enumeration, however, with the help of metaclass and dictionary, you can create your own enuemration.

 

 

let's see two impl, one is with a enum method by which you can further create any enumeration class.

 

 

First impl: enum meta method to create enumeration classes

 

 

 

The impl 

 

# define the __metaclass__ function
def M_add_class_attr(attribs):
    def foo(name, bases, dict_):
        for v, k in attribs:
            dict_[k] = v
        return type(name, bases, dict_)
    return foo

def enum(names):
    class Foo(object):
        __metaclass__ = M_add_class_attr(enumerate(names))
    def __setattr__(self, name, value): # this make it readonly
        raise NotImplementedError
    return Foo()
 

 

 

the test code 

 

 

import unittest

from MetaClass.EnumImpl1 import M_add_class_attr, enum
class Test(unittest.TestCase):


    def test_enumImpl1_usage_example(self):
        Animal = enum(['DOG', 'CAT'])
        self.assertEqual(0, Animal.DOG)
        self.assertEqual(1, Animal.CAT)
        


if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.test_enumImpl1_usage_example']
    unittest.main()
 

 

Second impl:  Enumeration Class with Symbol name

In this example, we are still going to create a animal enumeration class, and we want Animal to be a symbol rather than a variable where the client is able to reassign to.

 

 

the impl

 

class Animal(object):
    
    values = ["Horse", "Dog", "Cat"]
    
    # this is a very neat implementation
    # where you define a __metaclass__ method that 
    # has the __getattr__ override to return the index of the constants
    # that you have defined in class instance 'values'  

    class __metaclass__(type):
        def __getattr__(self, name):
            return self.values.index(name)
    
    # the above is equivalent as writting as follow.
#    class Animal_Metaclass(type):
#        def __getattr__(self, name):
#            return self.values.index(name)
#    __metaclass__ = Animal_Metaclass
 

 

the test code 

 

import unittest
from MetaClass.EnumImpl2 import Animal

class Test(unittest.TestCase):

    # though the syntax is not well recognized by the Eclispe IDE, the function works 
    # perfectly well.
    def test_enumImpl2_usage(self):
#        print Animal.Horse
        self.assertEqual(0, Animal.Horse)
        self.assertEqual(1, Animal.Dog)
        self.assertEqual(2, Animal.Cat)


if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.test_enumImpl2_usage']
    unittest.main()
 

 

 

 

分享到:
评论

相关推荐

    Python库 | django-enumeration-0.1.2.tar.gz

    资源分类:Python库 所属语言:Python 资源全名:django-enumeration-0.1.2.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    Python库 | optenum-1.1.6-py3-none-any.whl

    optenum是Python中一个专门处理枚举(enumeration)的库,它的全名是OptEnum,版本为1.1.6。这个库的设计目标是提供一个优化过的枚举实现,相较于Python内置的`enum`模块,它在某些特定场景下可能具有更高的性能和更...

    linux-smart-enumeration-master.zip

    linux-smart-enumeration-master.zip

    Python库 | cliquematch-1.2.0-cp38-cp38-win32.whl

    **Python库cliquematch-1.2.0-cp38-cp38-win32.whl详解** `cliquematch` 是一个专为Python设计的库,用于图论中的 clique 检测问题。Clique问题在数据挖掘、网络分析、社会网络等领域有广泛应用,它涉及到寻找图中...

    The-PS-enumeration-process-3.2.zip_The Process_列举进程

    "The-PS-enumeration-process-3.2.zip_The Process_列举进程"是一个与进程管理相关的项目,其目标是通过源码实现对系统中进程的枚举,即查找并列出所有正在运行的进程。在Windows系统中,这种功能通常由任务管理器...

    assignment-enumeration-python

    标题中的"assignment-enumeration-python"表明我们讨论的是一个与Python编程语言相关的任务,特别是涉及到枚举(Enumeration)方法在解决某种分配问题上的应用。枚举在编程中通常指的是遍历所有可能的状态或解决方案...

    linux-smart-enumeration:Linux枚举工具,用于具有详细级别的渗透测试和CTF

    首先,几个有用的one...linux-smart-enumeration 用于渗透测试和CTFLinux枚举工具 该项目的灵感来自并使用了许多测试。 不像LINENUM, lse尝试gradualy揭露根据其重要性从一个privesc点的信息。 它是什么? 该She

    Access-based Enumeration for sever 2003.zip

    Access-based Enumeration(基于访问权限的枚举)是Windows操作系统中的一项功能,特别是在Windows Server 2003中引入,用于改善文件服务器的用户体验。这项功能允许用户只看到他们有权限访问的文件和文件夹,而不是...

    C++出错提示英汉对照表

    Possible use of ''xxx'' before definition -------------------在定义之前就使用了xxx(警告) Possibly incorrect assignment ----------------赋值可能不正确 Redeclaration of ''xxx'' -------------------...

    Scanning-and-Enumeration-Automation-Tool-SEA

    扫描和枚举自动化工具SEA安装打开终端通过输入命令来创建虚拟环境:python3 -m venv SEA 通过输入以下命令激活虚拟环境:source SEA / bin / activate 使用以下命令安装python库:pip3 install -r requirements.txt ...

    Python-cvesearch是一种将CVE和CP导入MongoDB以便于搜索和处理CVE的工具

    Python-cvesearch是一款基于Python开发的安全相关工具,其主要功能是将CVE(Common Vulnerabilities and Exposures,常见漏洞和暴露)以及CPE(Common Platform Enumeration,通用平台枚举)数据导入到MongoDB数据库...

    python3.6.5参考手册 chm

    PEP 487: Simpler customization of class creation PEP 487: Descriptor Protocol Enhancements PEP 519: Adding a file system path protocol PEP 495: Local Time Disambiguation PEP 529: Change Windows ...

    Linux提权信息收集工具-linux-smart-enumeration

    信息收集工作整合成自动化脚本。该工具也是纯bash脚本,通用性较好,与LinPEAS类似,但收集的信息不如LinPEAS全面,但会关注一些LinPEAS没有关注到的信息,二者可结合使用,保证提权信息的全面性,防止遗漏。

    Python库 | matrix_enum-1.1.0-py2.py3-none-any.whl

    "Python库 | matrix_enum-1.1.0-py2.py3-none-any.whl" 这个标题指出了我们正在讨论的是一个针对Python编程语言的库,名为 "matrix_enum",并且它的版本号是1.1.0。"py2.py3-none-any" 部分说明了这个库兼容Python 2...

    Introduction to Computation and Programming Using Python

    ### 知识点一:Python编程基础 #### 标题与描述解读 - **标题**:“Introduction to Computation and Programming Using Python”(使用Python进行计算和编程导论) - **描述**:“Introduction to Computation and...

    Process--thread-enumeration.rar_delphi thread_delphi枚举进程_进程的线程

    在Delphi编程环境中,进程和线程的管理是操作系统级编程的重要组成部分。本文将深入探讨如何在Delphi中进行进程和线程的枚举,以及如何利用窗体组件调用例程来实现相关功能。 首先,我们要理解进程与线程的基本概念...

    Nosql-MongoDB-injection-username-password-enumeration:使用此脚本,您可以枚举Nosql(mongodb)注入易受攻击的Web应用程序的用户名和密码。

    网站: : 怎么跑用法nosqli-user-pass-enum.py [-h] [-u URL] [-up parameter] [-pp parameter] [-op parameters] [-ep parameter] [-sc character] [-m Method]例子python nosqli-user-pass-enum.py -u ...

    Introduction To Computation And Programming Using Python

    - 穷举枚举(Exhaustive Enumeration):通过逐一枚举所有可能值来解决问题,例如查找列表中的最大值或最小值。 - for循环(For Loops):一种简单有效的迭代结构,允许我们执行一段代码指定次数。 - 近似解决方案与...

Global site tag (gtag.js) - Google Analytics