欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

Python中的枚舉類型是什么-創(chuàng)新互聯(lián)

創(chuàng)新互聯(lián)www.cdcxhl.cn八線動(dòng)態(tài)BGP香港云服務(wù)器提供商,新人活動(dòng)買多久送多久,劃算不套路!

網(wǎng)站建設(shè)、基于html5技術(shù)的Web開發(fā)、手機(jī)站開發(fā)、微信開發(fā)等互聯(lián)網(wǎng)應(yīng)用服務(wù)。創(chuàng)新互聯(lián)始終關(guān)注著互聯(lián)網(wǎng)行業(yè)的前沿動(dòng)態(tài),創(chuàng)新互聯(lián)堅(jiān)信:真誠的態(tài)度,勤奮的工作是我們贏得客戶信賴的基礎(chǔ);而不斷創(chuàng)新、力求完美,才是創(chuàng)新互聯(lián)共同邁向美好未來的保證。

這篇文章將為大家詳細(xì)講解有關(guān)Python中的枚舉類型是什么,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

在Python中,枚舉和我們在對(duì)象中定義的類變量時(shí)一樣的,每一個(gè)類變量就是一個(gè)枚舉項(xiàng),訪問枚舉項(xiàng)的方式為:類名加上類變量。

雖然這樣是可以解決問題的,但是并不嚴(yán)謹(jǐn),也不怎么安全,比如:

1、枚舉類中,不應(yīng)該存在key相同的枚舉項(xiàng)(類變量)

2、不允許在類外直接修改枚舉項(xiàng)的值

Python中的枚舉類型是什么

下面來看看如何實(shí)現(xiàn)枚舉類型:

import operator
class EnumValue(object):
    def __init__(self, parent_name, name, value):
        self._parent_name = parent_name
        self._name = name
        self._value = value
    def _parents_equal(self, other):
        return (
            hasattr(other, '_parent_name')
            and self._parent_name == other._parent_name)
    def _check_parents_equal(self, other):
        if not self._parents_equal(other):
            raise TypeError(
                'This operation is valid only for enum values of the same type')
    def __eq__(self, other):
        return self._parents_equal(other) and self._value == other._value
    def __ne__(self, other):
        return not self.__eq__(other)
    def __lt__(self, other):
        self._check_parents_equal(other)
        return self._value < other._value
    def __le__(self, other):
        self._check_parents_equal(other)
        return self._value <= other._value
    def __gt__(self, other):
        self._check_parents_equal(other)
        return self._value > other._value
    def __ge__(self, other):
        self._check_parents_equal(other)
        return self._value >= other._value
    def __hash__(self):
        return hash(self._parent_name + str(self._value))
    def __repr__(self):
        return '{}({!r}, {!r}, {!r})'.format(
            self.__class__.__name__, self._parent_name, self._name, self._value)
    def __int__(self):
        return int(self._value)
    def __str__(self):
        return str(self._name)
class EnumMetaclass(type):
    def __new__(cls, name, bases, dct):
        uppercased = dict((k.upper(), v) for k, v in dct.items())
        new_dct = dict(
            name=name,
            _enums_by_str=dict(
                (k, EnumValue(name, k, v)) for k, v in uppercased.items()),
            _enums_by_int=dict(
                (v, EnumValue(name, k, v)) for k, v in uppercased.items()),
        )
        return super(EnumMetaclass, cls).__new__(cls, name, bases, new_dct)
    def __getattr__(cls, name):
        try:
            return cls.__getitem__(name)
        except KeyError:
            raise AttributeError
    def __getitem__(cls, name):
        try:
            name = name.upper()
        except AttributeError:
            pass
        try:
            return cls._enums_by_str[name]
        except KeyError:
            return cls._enums_by_int[name]
    def __repr__(cls):
        return '{}({!r}, {})'.format(
            cls.__class__.__name__,
            cls.name,
            ', '.join('{}={}'.format(v._name, v._value)
                      for v in sorted(cls._enums_by_str.values())))
    def values(cls):
        return sorted(cls._enums_by_str.values())
    def _values_comparison(cls, item, comparison_operator):
        """
        Return a list of values such that comparison_operator(value, item) is
        True.
        """
        return sorted(
            [v for v in cls._enums_by_str.values()
             if comparison_operator(v, item)])
    def values_lt(cls, item):
        return cls._values_comparison(item, operator.lt)
    def values_le(cls, item):
        return cls._values_comparison(item, operator.le)
    def values_gt(cls, item):
        return cls._values_comparison(item, operator.gt)
    def values_ge(cls, item):
        return cls._values_comparison(item, operator.ge)
    def values_ne(cls, item):
        return cls._values_comparison(item, operator.ne)
def enum_factory(name, **kwargs):
    return EnumMetaclass(name, (), kwargs)

Python中枚舉的測試:

import unittest
class EnumTestCase(unittest.TestCase):
    def test_repr(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertEqual(
            repr(ProfileAction),
            "EnumMetaclass('ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)")
    def test_value_repr(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertEqual(
            repr(ProfileAction.VIEW), "EnumValue('ProfileAction', 'VIEW', 1)")
    def test_attribute_error(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        with self.assertRaises(AttributeError):
            ProfileAction.ASDFASDF
    def test_cast_to_str(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertEqual(str(ProfileAction.VIEW), 'VIEW')
    def test_cast_to_int(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertEqual(int(ProfileAction.VIEW), 1)
    def test_access_by_str(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertEqual(ProfileAction['VIEW'], ProfileAction.VIEW)
    def test_access_by_int(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertEqual(ProfileAction[1], ProfileAction.VIEW)
    def test_equality(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertEqual(ProfileAction.VIEW, ProfileAction.VIEW)
        self.assertEqual(ProfileAction['VIEW'], ProfileAction.VIEW)
        self.assertEqual(ProfileAction[1], ProfileAction.VIEW)
    def test_inequality(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertNotEqual(ProfileAction.VIEW, ProfileAction.EDIT_OWN)
        self.assertNotEqual(ProfileAction['VIEW'], ProfileAction.EDIT_OWN)
        self.assertNotEqual(ProfileAction[1], ProfileAction.EDIT_OWN)
        DashboardAction = enum_factory(
            'DashboardAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertNotEqual(ProfileAction.VIEW, DashboardAction.VIEW)
    def test_invalid_comparison(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        DashboardAction = enum_factory(
            'DashboardAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        with self.assertRaises(TypeError) as cm:
            ProfileAction.VIEW < DashboardAction.EDIT_OWN
        self.assertEqual(
            str(cm.exception),
            'This operation is valid only for enum values of the same type')
    def test_values(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertEqual(
            ProfileAction.values(), [
                EnumValue('ProfileAction', 'VIEW', 1),
                EnumValue('ProfileAction', 'EDIT_OWN', 2),
                EnumValue('ProfileAction', 'EDIT_PUBLIC', 3),
                EnumValue('ProfileAction', 'EDIT_FULL', 4),
            ])
    def test_values_lt(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertEqual(
            ProfileAction.values_lt(ProfileAction.EDIT_PUBLIC), [
                EnumValue('ProfileAction', 'VIEW', 1),
                EnumValue('ProfileAction', 'EDIT_OWN', 2),
            ])
    def test_values_le(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertEqual(
            ProfileAction.values_le(ProfileAction.EDIT_PUBLIC), [
                EnumValue('ProfileAction', 'VIEW', 1),
                EnumValue('ProfileAction', 'EDIT_OWN', 2),
                EnumValue('ProfileAction', 'EDIT_PUBLIC', 3),
            ])
    def test_values_gt(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertEqual(
            ProfileAction.values_gt(ProfileAction.EDIT_PUBLIC), [
                EnumValue('ProfileAction', 'EDIT_FULL', 4),
            ])
    def test_values_ge(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertEqual(
            ProfileAction.values_ge(ProfileAction.EDIT_PUBLIC), [
                EnumValue('ProfileAction', 'EDIT_PUBLIC', 3),
                EnumValue('ProfileAction', 'EDIT_FULL', 4),
            ])
    def test_values_ne(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        self.assertEqual(
            ProfileAction.values_ne(ProfileAction.EDIT_PUBLIC), [
                EnumValue('ProfileAction', 'VIEW', 1),
                EnumValue('ProfileAction', 'EDIT_OWN', 2),
                EnumValue('ProfileAction', 'EDIT_FULL', 4),
            ])
    def test_intersection_with_same_type(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        set_a = set([ProfileAction.VIEW, ProfileAction.EDIT_OWN])
        set_b = set([ProfileAction.VIEW, ProfileAction.EDIT_PUBLIC])
        self.assertEqual(set_a & set_b, set([ProfileAction.VIEW]))
    def test_intersection_with_different_types(self):
        ProfileAction = enum_factory(
            'ProfileAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        DashboardAction = enum_factory(
            'DashboardAction', VIEW=1, EDIT_OWN=2, EDIT_PUBLIC=3, EDIT_FULL=4)
        set_a = set([ProfileAction.VIEW, ProfileAction.EDIT_OWN])
        set_b = set([DashboardAction.VIEW, DashboardAction.EDIT_PUBLIC])
        self.assertEqual(set_a & set_b, set([]))

關(guān)于Python中的枚舉類型是什么就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

新聞名稱:Python中的枚舉類型是什么-創(chuàng)新互聯(lián)
URL地址:http://chinadenli.net/article14/dgpgde.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站營銷網(wǎng)站策劃、Google靜態(tài)網(wǎng)站、小程序開發(fā)云服務(wù)器

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

綿陽服務(wù)器托管