Hướng dẫn can enum have multiple values python? - enum có thể có nhiều giá trị python không?

Sử dụng MultivalueEnum để nhận được nhiều giá trị trong Python. Bạn phải cài đặt và nhập thư viện

from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))
1 và đây là cách dễ nhất.

Mã ví dụ đơn giản.

from aenum import MultiValueEnum


class DType(MultiValueEnum):
    float32 = "f", 8
    double64 = "d", 9


print(DType("f"))
print(DType(9))

Output::

Hướng dẫn can enum have multiple values python? - enum có thể có nhiều giá trị python không?

Cách khác nhận được nhiều giá trị enum

from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))

Output::

DType.float32DType.double64
DType.double64

Hãy bình luận nếu bạn có bất kỳ nghi ngờ và đề xuất nào về chủ đề enum Python này.

Lưu ý: IDE: & NBSP; Pycharm & NBSP; 2021.3.3 (Phiên bản cộng đồng) IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

Tất cả & nbsp; ví dụ python & nbsp; là trong & nbsp; Python & nbsp; 3, vì vậy có thể khác với các phiên bản Python 2 hoặc nâng cấp. Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Hướng dẫn can enum have multiple values python? - enum có thể có nhiều giá trị python không?

Bằng cấp về Khoa học máy tính và Kỹ sư: Nhà phát triển ứng dụng và có nhiều ngôn ngữ lập trình kinh nghiệm. Sự nhiệt tình cho công nghệ và thích học kỹ thuật.

Trong khi Grokking mã nguồn của mô -đun

from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))
2, tôi đã bắt gặp kỹ thuật này để thêm các thuộc tính bổ sung vào các giá trị của các thành viên ENUM. Bây giờ, để hiểu ý tôi là gì khi thêm các thuộc tính, hãy xem xét ví dụ sau:

# src.py
from __future__ import annotations

from enum import Enum


class Color(str, Enum):
    RED = "Red"
    GREEN = "Green"
    BLUE = "Blue"

Ở đây, tôi đã được thừa hưởng từ

from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))
3 để đảm bảo rằng các giá trị của các thành viên ENUM là chuỗi. Lớp này có thể được sử dụng như sau:

# src.py
...

# Print individual members.
print(f"{Color.RED=}")

# Print name as a string.
print(f"{Color.GREEN.name=}")

# Print value.
print(f"{Color.BLUE.value=}")

Chạy tập lệnh sẽ in:

Color.RED=
Color.GREEN.name='GREEN'
Color.BLUE.value='Blue'

Mặc dù điều này hoạt động nhưng rõ ràng là bạn chỉ có thể gán một giá trị duy nhất cho một thành viên enum. Làm thế nào bạn viết lại điều này nếu bạn cần nhiều giá trị được đính kèm với một thành viên enum duy nhất?

Giả sử, trong trường hợp trên, cùng với tiêu đề màu, bạn cũng cần lưu các mã hex và mô tả ngắn về màu sắc. Một cách bạn có thể đạt được điều này là thông qua việc gán một thùng chứa bất biến là giá trị của một thành viên enum:

# src.py
from __future__ import annotations

from enum import Enum


class Color(Enum):
    RED = ("Red", "#ff0000", "Ruby Red")
    GREEN = ("Green", "#00ff00", "Guava Green")
    BLUE = ("Blue", "#0000ff", "Baby Blue")

Ở đây, tôi đang sử dụng một tuple để chứa tiêu đề, mã hex và mô tả của các thành viên

from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))
4. Điều này trở nên khó xử bất cứ khi nào bạn cần truy cập vào các yếu tố riêng lẻ bên trong tuple. Bạn sẽ phải sử dụng các chỉ mục được mã hóa cứng để truy cập vào các yếu tố của tuple. Đây là cách bạn có thể sử dụng nó:

...

for c in Color:
    print(
        f"title={c.value[0]}, hex_code={c.value[1]}, description={c.value[2]}"
    )

Nó in:

title=Red, hex_code=#ff0000, description=Ruby Red
title=Green, hex_code=#00ff00, description=Guava Green
title=Blue, hex_code=#0000ff, description=Baby Blue

Các chỉ mục mã hóa theo cách như vậy rất mong manh và sẽ bị phá vỡ nếu bạn bỏ một giá trị mới ở giữa tuple được gán cho một thành viên enum. Ngoài ra, thật khó để có lý do thông qua logic khi bạn giữ ý nghĩa ngữ nghĩa của các vị trí chỉ mục trong bộ nhớ làm việc của bạn. Một điều tốt hơn để làm là viết lại enum theo cách cho phép bạn truy cập các yếu tố khác nhau của các giá trị thành viên bằng tên thuộc tính của chúng. Hãy làm nó:

from __future__ import annotations

from enum import Enum


class Color(str, Enum):
    # Declaring the additional attributes here keeps mypy happy.
    hex_code: str
    description: str

    def __new__(
        cls, title: str, hex_code: str = "", description: str = ""
    ) -> Color:

        obj = str.__new__(cls, title)
        obj._value_ = title

        obj.hex_code = hex_code
        obj.description = description
        return obj

    RED = ("Red", "#ff0000", "Ruby Red")
    GREEN = ("Green", "#00ff00", "Guava Green")
    BLUE = ("Blue", "#0000ff", "Baby Blue")

Ở đây, tôi vượt qua phương thức

from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))
5 của lớp
from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))
4. Phương pháp
from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))
5 là một phương pháp lớp đặc biệt mà bạn không cần trang trí với bộ trang trí
from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))
8. Nó được thực thi trong quá trình tạo đối tượng
from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))
4; trước phương thức
# src.py
from __future__ import annotations

from enum import Enum


class Color(str, Enum):
    RED = "Red"
    GREEN = "Green"
    BLUE = "Blue"
0. Khác với đối số đầu tiên
# src.py
from __future__ import annotations

from enum import Enum


class Color(str, Enum):
    RED = "Red"
    GREEN = "Green"
    BLUE = "Blue"
1, bạn có thể xác định phương thức
from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))
5 với bất kỳ số lượng đối số được đặt tên tùy ý nào.

Trong trường hợp này, giá trị của mỗi thành viên của

from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))
4 sẽ có ba yếu tố. Vì vậy, tôi đã xác định phương pháp
from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))
5 để chấp nhận các đối số đó. Trong dòng sau, lớp
from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))
3 đã được khởi tạo thông qua
# src.py
from __future__ import annotations

from enum import Enum


class Color(str, Enum):
    RED = "Red"
    GREEN = "Green"
    BLUE = "Blue"
9 và sau đó
# src.py
from __future__ import annotations

from enum import Enum


class Color(str, Enum):
    RED = "Red"
    GREEN = "Green"
    BLUE = "Blue"
4 được gán cho đối tượng chuỗi mới được tạo thông qua
# src.py
...

# Print individual members.
print(f"{Color.RED=}")

# Print name as a string.
print(f"{Color.GREEN.name=}")

# Print value.
print(f"{Color.BLUE.value=}")
1. Dòng này là rất quan trọng; Không có nó, enum sẽ không hoạt động chút nào. Nhiệm vụ này đảm bảo rằng
# src.py
...

# Print individual members.
print(f"{Color.RED=}")

# Print name as a string.
print(f"{Color.GREEN.name=}")

# Print value.
print(f"{Color.BLUE.value=}")
2 sẽ trả về giá trị chuỗi.

Trong hai dòng tiếp theo,

# src.py
from __future__ import annotations

from enum import Enum


class Color(str, Enum):
    RED = "Red"
    GREEN = "Green"
    BLUE = "Blue"
5 và
# src.py
from __future__ import annotations

from enum import Enum


class Color(str, Enum):
    RED = "Red"
    GREEN = "Green"
    BLUE = "Blue"
6 đã được gắn vào các giá trị thành viên thông qua các câu lệnh
# src.py
...

# Print individual members.
print(f"{Color.RED=}")

# Print name as a string.
print(f"{Color.GREEN.name=}")

# Print value.
print(f"{Color.BLUE.value=}")
5 và
# src.py
...

# Print individual members.
print(f"{Color.RED=}")

# Print name as a string.
print(f"{Color.GREEN.name=}")

# Print value.
print(f"{Color.BLUE.value=}")
6 tương ứng.

Bây giờ, bạn sẽ có thể sử dụng enum này mà không cần bất kỳ shenanigans mã hóa cứng nào:

...

# Access the elements of the values of the members by names.
print(f"{Color.RED.value=}")
print(f"{Color.BLUE.hex_code=}")
print(f"{Color.GREEN.description=}")

# Iterate through all the memebers.
for c in Color:
    print(
        f"title={c.value}, hex_code={c.hex_code}, description={c.description}"
    )

Điều này sẽ in:

from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))
0

Người giới thiệu¶

  • http.HTTPStatus

Một enum có thể là nhiều giá trị?

Trình xây dựng Enum có thể chấp nhận nhiều giá trị..

Enum có thể có hai giá trị tương tự Python không?

Giới thiệu về các bí danh Enum theo định nghĩa, các giá trị thành viên liệt kê là duy nhất.Tuy nhiên, bạn có thể tạo các tên thành viên khác nhau với cùng một giá trị.you can create different member names with the same values.

Enum có thể có bao nhiêu giá trị?

Về lý thuyết, một cột enum có thể có tối đa 65.535 giá trị riêng biệt;Trong thực tế, mức tối đa thực sự phụ thuộc vào nhiều yếu tố.Các giá trị enum được thể hiện nội bộ dưới dạng số nguyên.65,535 distinct values; in practice, the real maximum depends on many factors. ENUM values are represented internally as integers.

Tôi có thể thêm các giá trị trong enum không?

Để thêm các giá trị mới vào enum, bạn nên mở rộng enum.you should extend the enum.